How to parse JSON structured-JSON Array Object in Java - java

i'm trying to parse this JSON code
{
"resultCode":"350",
"message":"OK",
"result":1,
"data":
{
"totalCount":"2",
"videos":[
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample1",
"description":""
},
{
"videoId":"73bfedf534",
"VideoUrl":"www.videourlexample.com",
"title":"vbsample2",
"description":""
}
]
}
}
I was able to parse only this.
"resultCode":"350",
"message":"OK",
"result":1,
this is the java code
JSONObject jsonObject = (JSONObject)
//return the JSON code above.
jsonParser.parse(getHTML("...httpRequest..."));
// get a String from the JSON object
String resultCode = (String) jsonObject.get("resultCode");
System.out.println("[RESULTCODE] The message is: " + resultCode);
// get a String from the JSON object
String message = (String) jsonObject.get("message");
System.out.println("[MESSAGE] The message is: " + message);
// get a number from the JSON object
long result = (long) jsonObject.get("result");
System.out.println("[RESULT] The resultCode is: " + result);
I can't parse the "data". Someone can help me?
I would like to take each value from the json array separately... like resultCode, message and result.
Thank you.

JSONObject mainObj= new JSONObject(yourJSON);
String resultCode= mainObj.get("resultCode");
String message= mainObj.get("message");
String result= mainObj.get("result");
JSONObject dataObj = mainObj.get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
JSONObject obj= jsonArray.get(i);
String videoId=obj.get("videoId");
String videoUrl=obj.get("VideoUrl");
String title=obj.get("title");
String description=obj.get("description");
System.out.println("videoId="+videoId +"videoUrl="+videoUrl+"title=title"+"description="+description);
}
System.out.println("resultCode"+resultCode+"message"+message+"result"+result);

You can try using this:-
JSONObject dataObj = (JSONObject)dataObj .get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
System.out.println(((JSONObject)jsonArray.get(i)).get("videoUrl"));
}
Currently I have just printes videoUrl, you can similarly get other attributes for videos.

for data use:
int totalCount = (int) ((Map) jsonObject.get("data")).get("totalCount");
JSONArray videos = (JSONArray) jsonObject.get("data")).get("videos");
and then parse videos JSONArray.

Related

Reading a JSON Array in JAVA

I'm having a problem reading JSON Array because inside my array, there's another array and I'm confused.Please see my code.
JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
JSONObject obj = JSONFactoryUtil.createJSONObject();
JSONObject jsonObjectReturn = JSONFactoryUtil.createJSONObject();
//JSONOBJECT RETURN
JSONArray array = JSONFactoryUtil.createJSONArray();
for (int i = 0; i < jsonArray.length(); i++) {
obj = jsonArray.getJSONObject(i);
callableStatement = (CallableStatement) conn
.prepareCall("{call TaxpaymentSPv2(?,?,?,?,?,?,?,?)}");
callableStatement.setString(1, obj.getString("rdoCode"));
callableStatement.setString(2, obj.getString("rcoCode"));
callableStatement.setString(3, obj.getString("tpTin"));
callableStatement.setString(4, obj.getString("tpName"));
callableStatement.setString(5, obj.getString("tpAddress"));
callableStatement.setString(6, obj.getString("receiptType"));
callableStatement.registerOutParameter(7, Types.VARCHAR);
callableStatement.registerOutParameter(8, Types.VARCHAR);
callableStatement.executeUpdate();
String rNo = callableStatement.getString(7);
String date = callableStatement.getString(8);
//---->This is my second Array inside my JSON where im having an error <------
String checkArray = obj.getString("checkArray");
JSONArray jsonArrayCheck = JSONFactoryUtil.createJSONArray(stringArray);
JSONArray jsonArray2 = jsonObject.getJSONArray("checkArray");
System.out.println("..........." + jsonArray2);
jsonObjectReturn = JSONFactoryUtil.createJSONObject();
jsonObjectReturn.put("rNo", rNo);
jsonObjectReturn.put("date", date);
array.put(jsonObjectReturn);
}
return array;
Here's my JSON input:
{
"dataArray": [{
"rdoCode": "001",
"rcoCode": "002911",
"tpTin": "200746409",
"tpName": "JOHN DOE",
"tpAddress": "LA CALIFORNIA",
"receiptType":"ROR",
"receiptMode":"AUTO",
"manualReceiptNo":"",
"checkArray":[{
"ptchkNumber": 14546,
"ptchkDate": 2014-01-01,
"ptchkAmount": 5332,
"ptchkStatus": ""
}]
}]
}
I can't parse the "checkArray" object that gives me this error. com.liferay.portal.kernel.json.JSONException: org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]. Can someone tell me what to do? Thanks.
You need to change code:
String checkArray = obj.getString("checkArray");
to following code:
JSONArray checkArray = obj.getJSONArray("checkArray");
JSONObject checkObj = checkArray.getJSONObject(0);
int ptchkNumber = checkObj.getInt("ptchkNumber");
because key checkArray is array inside JSON, so you cannot using getString() but getJSONArray() instead.
Update:
To get each object inside array, you can iterate and access each object:
JSONArray checkArray = obj.getJSONArray("checkArray");
JSONObject checkObj;
for (int itemIndex=0, totalObject = checkArray.length(); itemIndex < totalObject; itemIndex++) {
checkObj = checkArray.getJSONObject(itemIndex);
int ptchkNumber = checkObj.getInt("ptchkNumber");
}

Json Parse Exception: unable to find value in json array

after sorting by ascending order the below is the json array i am getting
[{"id":0,"dependency":"no","position":0,"Itype":"textinput","label":"t01"},{"id":0,"dependency":"no","position":1,"label":"t02","type":"textarea"},{"id":1,"dependency":"no","position":2,"type":"textinput","label":"t03"},{"id":1,"dependency":"no","position":3,"type":"textarea","label":"t04"}]
I am building up text field or textaaarea according to type or itype in json array but am getting exception "NO value for id"
This is the code so far
//Sorting function called
org.json.JSONArray finalSortedarray=Sort.Sort(formdataArray);
System.out.println("After Function Called Array------------>"+finalSortedarray);
/*for(int v=0;v<finalSortedarray.length();v++){
String sv=(String) formdataArray.getJSONObject(v).get("type");
System.out.println(sv);
}*/
for(int v=0;v<finalSortedarray.length();v++){
JSONObject obj1=(JSONObject)finalSortedarray.getJSONObject(v);
Iterator<String> Nkeys= obj1.keys();
while(Nkeys.hasNext()){
String Nkey=Nkeys.next();
JSONArray Nval=obj.getJSONArray(Nkey);
System.out.println("NVAL IS----->"+Nval);
//formdataArray.getJSONObject(v).get("type");
}
}
Please Help
for(int v=0;v<finalSortedarray.length();v++){
JSONObject obj1=(JSONObject)finalSortedarray.getJSONObject(v);
String id = obj1.getString("id");
String dependency= obj1.getString("dependency");
String position= obj1.getString("position");
//...
}
use like this
try{
JSONArray array = new JSONArray(response)
for(int i = 0; i<array.length();i++)
{
JSONObject obj1 = array.getJSONObject(i);
String id = obj1.getString("id");
String dependency= obj1.getString("dependency");
String position= obj1.getString("position");
String Itype= obj1.getString("Itype");
String label= obj1.getString("label");
}
}
catch(Exception e){
Log.d("","Error : "+e.toString());
}
happy to help

Parsing JSON of a particular case

I am trying retrieving the following JSON data from imagga's image recognition API.
{"results":[{"image":"http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg","tagging_id":null,"tags":[{"confidence":63.346307851163395,"tag":"valley"},{"confidence":60.66263009377379,"tag":"mountain"},{"confidence":44.39096006516168,"tag":"canyon"},{"confidence":42.08210930346856,"tag":"landscape"},{"confidence":33.52198895357515,"tag":"geological formation"},{"confidence":32.702112467737216,"tag":"mountains"},{"confidence":28.626223994488203,"tag":"glacier"},{"confidence":28.36,"tag":"natural depression"},{"confidence":28.03481906795487,"tag":"ravine"},{"confidence":27.269738461024804,"tag":"sky"},{"confidence":26.130797131953397,"tag":"rock"},{"confidence":23.11898739400327,"tag":"travel"},{"confidence":21.75182989551758,"tag":"alp"},{"confidence":20.956625061326214,"tag":"national"},{"confidence":20.15360199670358,"tag":"park"},{"confidence":19.826365024393702,"tag":"stone"},{"confidence":19.717420656127437,"tag":"water"},{"confidence":18.049071926896588,"tag":"river"},{"confidence":17.81629840041474,"tag":"hill"},{"confidence":17.30594970410163,"tag":"tourism"},{"confidence":17.192663177192692,"tag":"clouds"},{"confidence":16.53588724897844,"tag":"scenic"},{"confidence":15.98967256769248,"tag":"peak"},{"confidence":15.792599629554461,"tag":"lake"},{"confidence":15.532788988165363,"tag":"scenery"},{"confidence":15.453814687301834,"tag":"snow"},{"confidence":15.232632664896412,"tag":"outdoors"},{"confidence":15.212304004139495,"tag":"range"},{"confidence":15.042325772263556,"tag":"hiking"},{"confidence":14.958759294889424,"tag":"tree"},{"confidence":14.78842712696222,"tag":"forest"},{"confidence":12.853490785491731,"tag":"grass"},{"confidence":12.242518977753525,"tag":"desert"},{"confidence":12.095999999999998,"tag":"natural elevation"},{"confidence":12.03899501602295,"tag":"america"},{"confidence":11.49381779097963,"tag":"environment"},{"confidence":11.250534926394025,"tag":"usa"},{"confidence":10.935999552280517,"tag":"panorama"},{"confidence":10.838870815021957,"tag":"trees"},{"confidence":10.77081532273937,"tag":"south"},{"confidence":10.385222667460749,"tag":"summer"},{"confidence":9.967993711501377,"tag":"cloud"},{"confidence":9.960797892906747,"tag":"wild"},{"confidence":9.840206836878211,"tag":"natural"},{"confidence":9.64736797817423,"tag":"geology"},{"confidence":9.622992778171428,"tag":"rocky"},{"confidence":9.5011692563878,"tag":"outdoor"},{"confidence":9.36921935993258,"tag":"wilderness"},{"confidence":9.360136841263397,"tag":"vacation"},{"confidence":9.295849004816608,"tag":"rocks"},{"confidence":9.200756690906687,"tag":"high"},{"confidence":9.098263071652019,"tag":"highland"},{"confidence":8.912795414022,"tag":"tourist"},{"confidence":8.871604649828521,"tag":"hike"},{"confidence":8.849249986309006,"tag":"landmark"},{"confidence":8.696713373486205,"tag":"cliff"},{"confidence":8.600291951670297,"tag":"scene"},{"confidence":8.535889495009538,"tag":"stream"},{"confidence":8.530021520404471,"tag":"sunny"},{"confidence":8.255077489679804,"tag":"altitude"},{"confidence":8.016191292928964,"tag":"trail"},{"confidence":7.9938748285500605,"tag":"autumn"},{"confidence":7.985278417869093,"tag":"california"},{"confidence":7.927492176055299,"tag":"spain"},{"confidence":7.774043777890904,"tag":"adventure"},{"confidence":7.560207874392119,"tag":"peaceful"},{"confidence":7.485827508554503,"tag":"fall"},{"confidence":7.283862421876644,"tag":"erosion"},{"confidence":7.272123549182718,"tag":"terrain"},{"confidence":7.24510515635207,"tag":"rural"},{"confidence":7.234934522337296,"tag":"vista"},{"confidence":7.092282542389207,"tag":"holiday"}]}]}
I am using http://www.java2s.com/Code/Jar/o/Downloadorgjson20130603jar.htm library.
My Java code is as follows:
String imageUrl = "http://docs.imagga.com/static/images/docs/sample/japan-605234_1280.jpg",
apiKey = "",
apiSecret = "";
// These code snippets use an open-source library. http://unirest.io/java
HttpResponse response = Unirest.get("https://api.imagga.com/v1/tagging")
.queryString("url", imageUrl)
.basicAuth(apiKey, apiSecret)
.header("Accept", "application/json")
.asJson();
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(response.getBody()); // json
System.out.print("hello");
JSONObject data1 = jObject.getJSONObject("results"); // get data
System.out.print(data1); // object
String projectname = data1.getString("tags"); // get the name
// from data.
System.out.print(projectname);
I am getting the error that
Exception in thread "main" org.json.JSONException:
JSONObject["results"] not found.
What I want to get is the list of "tag" and "confidence".
try this
JSONArray data1 = jObject.getJSONArray("results");
Edited Answer
String js = response.getBody().toString();
System.out.println(js.toString());
JSONObject jObject = new JSONObject(js); // json
System.out.print("hello");
JSONArray data1 = jObject.getJSONArray("results");
for(int i = 0; i < data1.length; i++)
{
JSONObject jsonObject = data1.getJSONObject(i);
String projectn ame = jsonObject.getString("tagging_id");
System.out.print(projectname);
JSONArray tagArray = jsonObject.getJsonArray("tags");
for(int j = 0; j < tagArray.length; j++)
{
JSONObject tagObject = tagArray.getJSON(j);
System.out.println("Tag == " + tagObject.getString("tag"));
}
}
To make your life more easy I'd go to model the Objects as POJO's and let Jackson's Objectmapper do the magic.
See http://wiki.fasterxml.com/JacksonDataBinding
I suppose you should try jObject.getJSONArray("results") instead of jObject.getJSONObject("results").
There is also a good tool to convert json to java: http://json2java.azurewebsites.net/
If you use it, you will see:
...other code...
public class RootObject
{
private ArrayList<Result> results;
public ArrayList<Result> getResults() { return this.results; }
public void setResults(ArrayList<Result> results) { this.results = results; }
}
...other code...
And results is list here, so use getJSONArray instead of getJSONObject
If you look into your json results has an array in it and therefore you should use getJSONArray and not getJSONObject.
JSONArray data1 = jObject.getJSONArray("results");

Parse JSON string in Java without keys

I am new to parsing JSON in java. I have this JSON string:
[
{
"projectId":5,
"userName":"clinician",
"projectName":"r",
"projectSummary":"r",
"projectLanguage":"r",
"contactPersonName":"r",
"contactPersonCV":"r",
"contactPersonEmail":"r",
"contactPersonPhone":"r"
},
[
{
"consentFileId":2,
"projectId":5,
"consentDescription":"r",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":null
},
{
"consentFileId":3,
"projectId":5,
"consentDescription":"rrr",
"consentFileName":"test.pdf",
"servicePathToGetConsentPdf":"localhost:8080/4c_viewFile?consentFileId=3"
}
],
[
{
"anonymized_patient_identifier":"r",
"projectId":5
},
{
"anonymized_patient_identifier":"2",
"projectId":5
},
{
"anonymized_patient_identifier":"5",
"projectId":5
}
]
]
I have managed to get values from simpler JSON strings but this one has multiple levels and also there is no key in each level. I tried with simple code like this:
Object obj = parser.parse(data);
JSONObject jsonObject = (JSONObject) obj;
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
but I get the error [java.lang.ClassCastException: org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject] And also I don't understand how I will get the values in lower level without a key. I tried also to save it as a JSONArray but it didn't work.
your root of json is type of JSONArray,
the first object stored in the root array is an object, you can retrieve it by using index = 0 .
this is a hack to make your code work:
JSONArray jsonArray = JSONArray.fromObject(data);
JSONObject jsonObject=obj.getJSONObject(0);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
NOTE:
to convert a String to JSONArray, you can do :
JSONArray array = JSONArray.fromObject(data);
To improve on nafas answer, I would do this to see all the objects in the array:
Object obj = parser.parse(data);
JSONArray jsonArray = (JSONArray) obj;
for (int i = 0; i < jsonArray.size (); i++) {
JSONObject jsonObject=obj.getJSONObject(i);
resultJson = (String) jsonObject.get("projectId");
resultJson += "\n";
resultJson += (String) jsonObject.get("userName");
}

Getting Json object inside a Json object in Java

So I have some code that is able to send this out:
{"id":1,
"method":"addWaypoint",
"jsonrpc":"2.0",
"params":[
{
"lon":2,
"name":"name",
"lat":1,
"ele":3
}
]
}
The server receives this JSON object as a string named "clientstring":
JSONObject obj = new JSONObject(clientstring); //Make string a JSONObject
String method = obj.getString("method"); //Pulls out the corresponding method
Now, I want to be able to get the "params" value of {"lon":2,"name":"name","lat":1,"ele":3} just like how I got the "method".
however both of these have given me exceptions:
String params = obj.getString("params");
and
JSONObject params = obj.getJSONObject("params");
I'm really at a loss how I can store and use {"lon":2,"name":"name","lat":1,"ele":3} without getting an exception, it's legal JSON yet it can't be stored as an JSONObject? I dont understand.
Any help is VERY appreciated, thanks!
params in your case is not a JSONObject, but it is a JSONArray.
So all you need to do is first fetch the JSONArray and then fetch the first element of that array as the JSONObject.
JSONObject obj = new JSONObject(clientstring);
JSONArray params = obj.getJsonArray("params");
JSONObject param1 = params.getJsonObject(0);
How try like that
JSONObject obj = new JSONObject(clientstring);
JSONArray paramsArr = obj.getJSONArray("params");
JSONObject param1 = paramsArr.getJSONObject(0);
//now get required values by key
System.out.println(param1.getInt("lon"));
System.out.println(param1.getString("name"));
System.out.println(param1.getInt("lat"));
System.out.println(param1.getInt("ele"));
Here "params" is not an object but an array. So you have to parse using:
JSONArray jsondata = obj.getJSONArray("params");
for (int j = 0; j < jsondata.length(); j++) {
JSONObject obj1 = jsondata.getJSONObject(j);
String longitude = obj1.getString("lon");
String name = obj1.getString("name");
String latitude = obj1.getString("lat");
String element = obj1.getString("ele");
}

Categories

Resources