我在java中有这个json:
jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}
jsonObj
是来自 API 的响应,因此我将其作为 jsonObject,并且不从任何文件中读取它。
是否有一种简单的方法可以像 jsonObj [1]
那样将所有值提取为个体?
最佳答案
您可以使用Gson解析库,如下所示:
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);
Gson gson = new Gson();
String jsonInString = "{\"userId\":\"1\",\"userName\":\"Yasir\"}";
User user= gson.fromJson(jsonInString, User.class);
或者简单地使用:
示例
JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse = object.getString("getIMEIResult");
用于数组:
//getting whole json string
JSONObject jsonObj = new JSONObject(jsonStr);
//extracting data array from json string
JSONArray ja_data = jsonObj.getJSONArray("data");
int length = jsonObj .length();
关于Java:将 json 值提取为个体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44928537/