问题
I am new to Gson and not very experienced with java. I have a list of json objects and then lists inside each object like this:
[
{
"A": 358584,
"B": "Apache",
"C": [
"Ethnicity",
"Ethnicity in fiction",
"American Indian group"
],
"D": 23.647824738317627,
"E": "Ethnicity",
"F": "Apache"
},
{
"A": 19283806,
"B": "San Jose",
"C": [
"Location",
"Employer",
"Region",
"Transit Service Area"
],
"D": 11.184500611578535,
"E": "Location",
"F": "San Francisco Bay Area"
}
]
I would appreciate a detailed or step by step answer on how to do this and which classes and methods to use.
回答1:
Did you try anything already (There are plenty of examples already availalbe online)?
Use google 'https://github.com/google/gson' library.
JSON format: <Attribute_Name> : <Value>
[] --> List or Array
{} --> Single Object
So now create a Java POJO just like JSON structure.
class Data {
private Integer A;
private String B;
private List<String> C;
private Double D;
private String E;
private String F;
}
Now use the GSON library to parse the string.
public static void main(String[] args) {
String data = "[{\"A\":358584,\"B\":\"Apache\",\"C\":[\"Ethnicity\",\"Ethnicity in fiction\",\"American Indian group\"],\"D\":23.647824738317627,\"E\":\"Ethnicity\",\"F\":\"Apache\"},{\"A\":19283806,\"B\":\"San Jose\",\"C\":[\"Location\",\"Employer\",\"Region\",\"Transit Service Area\"],\"D\":11.184500611578535,\"E\":\"Location\",\"F\":\"San Francisco Bay Area\"}]";
Data[] dataArray = (new Gson()).fromJson(data, Data[].class);
if (dataArray != null) {
System.out.println(dataArray.length);
}
}
来源:https://stackoverflow.com/questions/29833749/how-to-use-gson-to-parse-a-list-of-json-objects-with-nested-arrays