Java jsonobject get array

How to create correct JSONArray in Java using JSONObject

Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

An example of this using the builder pattern in java 7 looks something like this:

JsonObject jo = Json.createObjectBuilder() .add("employees", Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("firstName", "John") .add("lastName", "Doe"))) .build(); 

@PT_C yep JsonObject jo = Json.createObjectBuilder(); jo.add(«firstName», «John»); jo.add(«lastName», «Doe»); jo.build();

I suppose you’re getting this JSON from a server or a file, and you want to create a JSONArray object out of it.

String strJSON = ""; // your string goes here JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue(); // once you get the array, you may check items like JSONOBject jObject = jArray.getJSONObject(0); 

Small reusable method can be written for creating person json object to avoid duplicate code

JSONObject getPerson(String firstName, String lastName) < JSONObject person = new JSONObject(); person .put("firstName", firstName); person .put("lastName", lastName); return person ; >public JSONObject getJsonResponse()

Please try this . hope it helps

JSONObject jsonObj1=null; JSONObject jsonObj2=null; JSONArray array=new JSONArray(); JSONArray array2=new JSONArray(); jsonObj1=new JSONObject(); jsonObj2=new JSONObject(); array.put(new JSONObject().put("firstName", "John").put("lastName","Doe")) .put(new JSONObject().put("firstName", "Anna").put("v", "Smith")) .put(new JSONObject().put("firstName", "Peter").put("v", "Jones")); array2.put(new JSONObject().put("firstName", "John").put("lastName","Doe")) .put(new JSONObject().put("firstName", "Anna").put("v", "Smith")) .put(new JSONObject().put("firstName", "Peter").put("v", "Jones")); jsonObj1.put("employees", array); jsonObj1.put("manager", array2); Response response = null; response = Response.status(Status.OK).entity(jsonObj1.toString()).build(); return response; 

Источник

How to retrieve json array elements from JSON object in Java?

I have this JSONObject, and I want to be able to access elements in the array inside of it. The object opens successfully, I just don’t know how to access the array called «firstNames». It is in a file, and the object looks like this.

Читайте также:  Custom thread in java

Edit: I am using org.json.simple.JSONObject . If this is not recommended, I am more than willing to change it.

3 Answers 3

There are several ways to retrieve the json array value:

Assume we have a jsonString

(since many classes share similar names, I am using the groupId and artifactId for distinction.)

Simple cases: use generic JSONObjects and JSONArrays.

json-simple (which OP is using) json-simple website, maven :

org.json.simple.parser.JSONParser jsonParser = new org.json.simple.parser.JSONParser(); org.json.simple.JSONObject firstObject = (org.json.simple.JSONObject) jsonParser.parse(jsonString); org.json.simple.JSONArray jsonArray = (org.json.simple.JSONArray) firstObject.get("firstNames"); System.out.println(jsonArray); 

JSON in Java (mentioned in adendrata’s answer): JSON-Java doc, maven

org.json.JSONObject secondObject = new org.json.JSONObject(jsonString); org.json.JSONArray jsonArray2 = secondObject.getJSONArray("firstNames"); System.out.println(jsonArray2); 
com.google.gson.JsonObject thirdObject = com.google.gson.JsonParser.parseString(jsonString).getAsJsonObject(); System.out.println(thirdObject.get("firstNames").getAsJsonArray()); 

For more complicated use cases, if you’d like to define your own class, and want to deserialize JSON string to your class, then you can use Gson or Jackson:

 // Create your own class: /* public class YourOwnClass < private ListfirstNames; public List getFirstNames() < return firstNames; >> */ Gson gson = new Gson(); YourOwnClass customObject1 = gson.fromJson(jsonString, YourOwnClass.class); System.out.println(customObject1.getFirstNames()); ObjectMapper mapper = new ObjectMapper(); YourOwnClass customObject2 = mapper.readValue(jsonString, YourOwnClass.class); System.out.println(customObject2.getFirstNames()); 

Источник

How to extract JSONArray and JSONObject from a JSON in Java

You should share code you tried to apply against given problem. Can you also put more details about what kind of json library you use.

i’m using «json-simple» Library. and input is a @requestParam parameter of post api of Springboot project ,i want to save jsonObject in a different Collection and JsonArray in different Collection of mongodb. JSONObject is data member of a model class and JSON Array is a Diffrent model class in the Project

2 Answers 2

its pretty simple if you know java JSON API

String jsonString="< "messageName": "ReportCard", "orgId": "Org1", "comment": true, "Fields": [< "objectId": "1234-56789-asdv", "fieldId": "1245-7852-dhjd" >, < "objectId": "1234-56hgjgh789-hjjhj", "fieldId": "12sdf45-78sfg52-dfjhjd" >] >" JSONObject jObject= new JSONObject(jsonString); JSONObject jo = new JSONObject(); //creating new Jobject // putting data to JSONObject jo.put("messageName", jObject.getString("messageName").toString()); jo.put("orgId", jObject.getString("orgId").toString()); jo.put("comment", jObject.getString("comment").toString()); JSONArray Fields= jObject.getJSONArray("Fields");//extract field array JSONArray ja = new JSONArray(); //creating new json array. int Arraylength = Fields.length(); for(int i=0;i JSONObject fieldsObj = new JSONObject(); fieldsObj.put("Fields", ja); // Fields Array Created 

Источник

Читайте также:  Java bytes to number one

Converting JSONObject to JSONArray

I’m currently learning some android programming with JAVA. My teacher shared this piece of code which will consume an API, get its JSON file, and convert it to a JSONArray file. Then he will Iterate through that JSONArray and put them into an ArrayList before displaying them onto an activity. The problem is that the API that I’m consuming returns a JSONObject file instead, and I do not know how to properly convert this to JSONArray.

import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.HashMap; public class JSONParser < String charset = "UTF-8"; HttpURLConnection conn; DataOutputStream wr; StringBuilder result; URL urlObj; JSONArray jObj = null; StringBuilder sbParams; String paramsString; public JSONArray makeHttpRequest(String url, String method) < sbParams = new StringBuilder(); if(method.equals("GET"))< // request method is GET if (sbParams.length() != 0) < url += "?" + sbParams.toString(); >try < urlObj = new URL(url); conn = (HttpURLConnection) urlObj.openConnection(); conn.setDoOutput(false); conn.setRequestMethod("GET"); conn.setRequestProperty("AccountKey", "pVU56+0hI26DNLeTzlU/Dw=="); conn.setRequestProperty("UniqueUserId", "33c07f2f-b4c0-4151-acd3-e0829b303d2c"); conn.setRequestProperty("accept", "application/json"); conn.setConnectTimeout(15000); conn.connect(); >catch (IOException e) < e.printStackTrace(); >> try < //Receive the response from the server InputStream in = new BufferedInputStream(conn.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) < result.append(line); >Log.d("JSON Parser", "result: " + result.toString()); > catch (IOException e) < // e.printStackTrace(); >conn.disconnect(); // try parse the string to a JSON object try < jObj = new JSONArray(result.toString()); >catch (JSONException e) < Log.e("JSON Parser", "Error parsing data " + e.toString()); >// return JSON Object return jObj; > 
URL: http://datamall2.mytransport.sg/ltaodataservice/TaxiAvailability 
AccountKey: pVU56+0hI26DNLeTzlU/Dw== UniqueUserId: 33c07f2f-b4c0-4151-acd3-e0829b303d2c accept: application/json 

Источник

How to extract JSONArray and JSONObject from a JSON in Java

You should share code you tried to apply against given problem. Can you also put more details about what kind of json library you use.

Читайте также:  To-do CRUD

i’m using «json-simple» Library. and input is a @requestParam parameter of post api of Springboot project ,i want to save jsonObject in a different Collection and JsonArray in different Collection of mongodb. JSONObject is data member of a model class and JSON Array is a Diffrent model class in the Project

2 Answers 2

its pretty simple if you know java JSON API

String jsonString="< "messageName": "ReportCard", "orgId": "Org1", "comment": true, "Fields": [< "objectId": "1234-56789-asdv", "fieldId": "1245-7852-dhjd" >, < "objectId": "1234-56hgjgh789-hjjhj", "fieldId": "12sdf45-78sfg52-dfjhjd" >] >" JSONObject jObject= new JSONObject(jsonString); JSONObject jo = new JSONObject(); //creating new Jobject // putting data to JSONObject jo.put("messageName", jObject.getString("messageName").toString()); jo.put("orgId", jObject.getString("orgId").toString()); jo.put("comment", jObject.getString("comment").toString()); JSONArray Fields= jObject.getJSONArray("Fields");//extract field array JSONArray ja = new JSONArray(); //creating new json array. int Arraylength = Fields.length(); for(int i=0;i JSONObject fieldsObj = new JSONObject(); fieldsObj.put("Fields", ja); // Fields Array Created 

Источник

Оцените статью