I have the following JSON text (REST API URL SOURCE). How can I parse it to get ID, name, phone,city etc:
{"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"}
thanks.
EDIT:
I Run this code:
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);
and I got "phone" as a string . someone can add the code to parse the phone line?
asked Jun 6, 2018 at 9:46
eyal1506
1133 gold badges5 silver badges11 bronze badges
-
By using a JSON-Parser?Hulk– Hulk2018年06月06日 09:47:59 +00:00Commented Jun 6, 2018 at 9:47
-
oracle.com/technetwork/articles/java/json-1973242.htmlDmitri Gudkov– Dmitri Gudkov2018年06月06日 09:49:33 +00:00Commented Jun 6, 2018 at 9:49
-
4Possible duplicate of How to parse JSON in Javarjdkolb– rjdkolb2018年06月06日 09:49:42 +00:00Commented Jun 6, 2018 at 9:49
-
1For information, the "following JSON text" is malformed JSON. It looks like it is a text file, made of three JSON objects, one on each line. JSON format doesn't allow to just write several JSON objects one after the other without a structuring syntax linking them. No parser can fix that for you. ... But if they're all on their on line, you could always read the file line-by-line, and use a JSON parser on each line.kumesana– kumesana2018年06月06日 10:07:32 +00:00Commented Jun 6, 2018 at 10:07
2 Answers 2
You can use Gson to parse the JSON. Simply create a class for this and Gson will do the parsing for you.
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;
}
}
then in your main class or activity:
MyClass myclass= new Gson().fromJSON(jsonString,MyClass.class);
System.out.println(myclass.getID());
answered Jun 6, 2018 at 9:54
Anuran Barman
1,6862 gold badges18 silver badges36 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Make use of org.json libarary. Afterwards, create an instance of JSONObject and JSONArray to parse the JSON String
Comments
lang-java