问题
I get a json string in server side as follow
[ {"projectFileId":"8547",
"projectId":"8235",
"fileName":"1",
"application":"Excel",
"complexity":"NORMAL",
"pageCount":"2",
"targetLanguages":" ar-SA",
"Id":"8547"
},
{"projectFileId":"8450",
"projectId":"8235",
"fileName":"Capacity Calculator.pptx",
"application":"Powerpoint",
"complexity":"NORMAL",
"pageCount":"100",
"targetLanguages":" ar-LB, ar-SA",
"Id":"8450"
}
]
I want to convert this string into an arraylist or map whichever possible so that I can iterate over it and get the field values.
回答1:
You can use GSON library. Simply use Gson#fromJson() method to convert JSON string into Java Object.
sample code:
BufferedReader reader = new BufferedReader(new FileReader(new File("json.txt")));
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
ArrayList<Map<String, String>> data = gson.fromJson(reader, type);
// convert back to JSON string from object
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(data));
You can create a POJO class to convert it directly into List of POJO clas object to access it easily.
sample code:
class PojectDetail{
private String projectFileId;
private String projectId;
private String fileName;
private String application;
private String complexity;
private String pageCount;
private String targetLanguages;
private String Id;
// getter & setter
}
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<PojectDetail>>() {}.getType();
ArrayList<PojectDetail> data = gson.fromJson(reader, type);
来源:https://stackoverflow.com/questions/24939724/convert-json-string-to-list-or-map