gpt4 book ai didi

java - 在java中解析JSON(Eclipse)

转载 作者:行者123 更新时间:2023-11-30 02:08:42 25 4
gpt4 key购买 nike

我有以下 JSON 文本(REST API URL 源)。我如何解析它以获取 ID、姓名、电话、城市等:

{"ID":1,"name":"aaa","phone":["345345345","1244","743"],"city":"asdasd"}
{"ID":2,"name":"bbb","phone":["234234","235","124"]}
{"ID":3,"name":"ccc","phone":["4234","6236","123"],"city":"jhjk"}

谢谢。

编辑:

我运行此代码:

                      String var1 = output;
JSONObject obj;
try {
obj = new JSONObject(var1);
String a = obj.getString("name");
String b = obj.getString("phone");
String c = obj.getString("city");

System.out.println("name:" + a);
System.out.println("phone:" + b);
System.out.println("city:" + c);

我得到了“phone”作为字符串。有人可以添加代码来解析电话线吗?

最佳答案

您可以使用Gson解析 JSON。只需为此创建一个类,Gson 就会为您进行解析。

class MyClass{
@SerializedName("ID")
String ID;
@SerializedName("name")
String name;
@SerializedName("phone")
List<String> phone;
@SerializedName("city")
String city;

public MyClass(String ID, String name, List<String> phone, String city) {
this.ID = ID;
this.name = name;
this.phone = phone;
this.city = city;
}

public String getID() {
return ID;
}

public void setID(String ID) {
this.ID = ID;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<String> getPhone() {
return phone;
}

public void setPhone(List<String> phone) {
this.phone = phone;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}
}

然后在您的主类(class)或 Activity 中:

MyClass myclass= new Gson().fromJSON(jsonString,MyClass.class);
System.out.println(myclass.getID());

关于java - 在java中解析JSON(Eclipse),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50717229/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com