简体   繁体   中英

Java: Extract json values as individuals

I have this json in java:

jsonObj = {"ps":["2.16.840.1.113883.6.1","LOINC","2.34"]}

jsonObj is response from an API, so I have it as jsonObject and I don't read it from any file.

Is there an easy way to extract all the values as individuals like jsonObj [1] ?

You may Use Gson parsing library as below :

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);

or simply use:

example

JSONObject object = new JSONObject(your_json_response_string);
String IMEICheckResponse  = object.getString("getIMEIResult");

for Array use :

//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(); 

You should use a library to deserialize your JSON in a Java Object. Libraries like GSON , Genson or Jackson . Once you transform the json in a object, it will have a property called "ps" that will be an array (or a List)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM