刚开始,我是Java的新手。我正在尝试使用他们的API和Arduino为Twitch创建一个通知系统,而我目前几乎一开始就处于停滞状态。我可以访问API并获取信息,但是我不知道如何将其转换为有用的东西。这是我目前的代码。
public class commandRun {
public static void main(String[] args) {
Process p;
try {
p = Runtime.getRuntime().exec("cmd /c curl -H \"Client-ID: clientID\" -X GET \"https://api.twitch.tv/helix/users/follows?first=1&to_id=channelID\n");
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String twitchFollower;
while((twitchFollower = reader.readLine()) != null) {
System.out.println(twitchFollower);
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这将返回
{
"total": 106,
"data": [
{
"from_id": "followerID",
"from_name": "follower",
"to_id": "channelid",
"to_name": "channel",
"followed_at": "2019-10-06T21:03:03Z"
}
],
"pagination": {
"cursor": "dontknowifthisissensitiveinfo"
}
}
我希望能够从字符串中删除特定信息,例如关注者的姓名。
答案 0 :(得分:0)
jrook的注释有很多JSON库可以实现。
以下示例代码显示了最受欢迎的两种库- Jackson 和 Gson -如何获取特定字段的值。 (我假设关注者名称的键是 from_name 。)
// Jackson
ObjectMapper mapper = new ObjectMapper();
String followerName = mapper.readTree(jsonStr)
.get("data")
.get(0)
.get("from_name")
.asText();
System.out.println(followerName);
// Gson
followerName = new JsonParser().parse(jsonStr)
.getAsJsonObject()
.get("data")
.getAsJsonArray()
.get(0)
.getAsJsonObject()
.get("from_name")
.getAsString();
System.out.println(followerName);
控制台输出:
关注者
追随者