我在服务器端获得了一个json字符串,如下所示
[ {"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"
}
]
我希望将此字符串转换为arraylist或map尽可能使我可以迭代它并获取字段值。
答案 0 :(得分:2)
您可以使用GSON
library。只需使用Gson#fromJson()
方法将JSON字符串转换为Java Object。
示例代码:
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));
您可以创建一个POJO类,将其直接转换为POJO clas对象列表,以便轻松访问它。
示例代码:
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);