Java 将 json 字符串转换为列表或映射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24939724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert json string to list or map
提问by Mayur Sawant
I get a json string in server side as follow
我在服务器端得到一个 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"
}
]
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.
我想尽可能地将此字符串转换为数组列表或映射,以便我可以对其进行迭代并获取字段值。
回答by Braj
You can use GSON
library. Simply use Gson#fromJson()
method to convert JSON string into Java Object.
您可以使用GSON
库。只需使用Gson#fromJson()
方法将 JSON 字符串转换为 Java 对象。
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.
您可以创建一个 POJO 类将其直接转换为 POJO 类对象的 List 以轻松访问它。
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);