Getting attribute values from JSON String in Java - java

Hello I am building a Spring Boot app with Thymeleaf and I am receiving from an API a JSON that I have to put in the HTML page. This is the JSON:
{"mesaje":[{"data_creare":"202205191249","cif":"1111111111118","id_solicitare":"205804","detalii":"Erori de validare identificate la factura primita cu id_incarcare=205804","tip":"ERORI FACTURA","id":"9279339"}
This is what I have tried:
String raspuns = service.getListaMesaje(zile, select);
System.out.println("------------------------"+raspuns);
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(raspuns).getAsJsonObject();
//String eroare = obj.get("eroare").getAsString();
String mesaje = obj.get("mesaje").getAsString();
JSONObject responseObject = new JSONObject(raspuns);
JSONArray jsonArray = (JSONArray) responseObject.get("mesaje");
JSONObject jsonObject = (JSONObject) jsonArray.get(0);
String dataCreare = jsonObject.getString("data_creare");
model.addAttribute("data_creare", dataCreare);
In the console the JSON prints but I get this error also in the console:
java.lang.IllegalStateException: null
Can someone show me an example how to extract the values from mesaje parent in the JSON ?
Thank you

I suggest you to use gson library for that.
Then, after you added gson dependency in pom.xml, you can extract values from your JSON string with this few lines of code :
String raspuns = "{\"mesaje\":[{\"data_creare\":\"202205191249\",\"cif\":\"1111111111118\",\"id_solicitare\":\"205804\",\"detalii\":\"Erori de validare identificate la factura primita cu id_incarcare=205804\",\"tip\":\"ERORI FACTURA\",\"id\":\"9279339\"}]}";
JsonObject jsonObject = new JsonParser().parse(raspuns).getAsJsonObject();
JsonArray arr = jsonObject.getAsJsonArray("mesaje");
for (int i = 0; i < arr.size(); i++) {
String data_creare = arr.get(i).getAsJsonObject().get("data_creare").getAsString();
String cif = arr.get(i).getAsJsonObject().get("cif").getAsString();
String id_solicitare = arr.get(i).getAsJsonObject().get("id_solicitare").getAsString();
String detalii = arr.get(i).getAsJsonObject().get("detalii").getAsString();
String tip = arr.get(i).getAsJsonObject().get("tip").getAsString();
String id = arr.get(i).getAsJsonObject().get("id").getAsString();
System.out.println(data_creare);
System.out.println(cif);
System.out.println(tip);
System.out.println(id_solicitare);
System.out.println(detalii);
System.out.println(id);
}

Related

How do we extract Json in Play 2.8 ? We are upgrading to Play 2.8 framework

How do we extract Json in play 2.8? I am not finding many examples in Java.
The libraries com.google.gson is not supported any more . JsonArray , JsonElement and JsonObject are not supported any more. I have a method which extracts few values from Json String .
public static synchronized JsonArray getJsonPAIFromString(String jsonString) {
JsonArray jsonPAIArray = new JsonArray();
if (jsonString!=null && !jsonString.isEmpty()) {
JsonElement jelement = new JsonParser().parse(jsonString);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("result");
JsonArray jarray = jobject.getAsJsonArray("policyList");
for (int i = 0; i < jarray.size(); i++) {
jobject = jarray.get(i).getAsJsonObject();
JsonObject pai = jobject.get("pai").getAsJsonObject();
pai.add("policyHolderId", jobject.get("policyHolderId"));
pai.add("policyId", jobject.get("id"));
pai.add("policyNumber", jobject.get("number"));
jsonPAIArray.add(pai);
Logger.debug("Response : \n" + pai.toString());
}
}
return jsonPAIArray;
}
Play framework uses Jakson library for JSON transformation.
To transform a String into a JSON you can use this:
// parse the JSON as a JsonNode
JsonNode json = Json.parse("{\"firstName\":\"Foo\", \"lastName\":\"Bar\");

Incorrect JSONException

I'm trying to use JSON objects from the Guardian API.
This is the result from my call:
https://pastebin.com/wqggLEeZ
This is my code
JSONObject root = new JSONObject(jsonData);
JSONArray resultArray = root.getJSONObject("response").getJSONArray("results");
for(int i=0;i<resultArray.length();i++) {
JSONObject resultElement = resultArray.getJSONObject(i);
JSONObject blocksElement = resultElement.getJSONObject("blocks");
JSONObject mainElement = blocksElement.getJSONObject("main");
JSONArray elementsArray = mainElement.getJSONArray("elements");
JSONObject elementsElement = elementsArray.getJSONObject(0);
JSONArray assetsArray = elementsElement.getJSONArray("assets");
JSONObject assetsElement = assetsArray.getJSONObject(0);
String imageUrl = assetsElement.getString("file");
String articleTitle = resultElement.getString("webTitle");
news.add(new NewsList(articleTitle, imageUrl));
}
The code works fine except that it stops at 3 elements (i=2)
I tried replacing the imageUrl with "test" string in
news.add(new NewsList(articleTitle, imageUrl));
but it still stops at 3 elements.
But when I comment out the part where it finds the imageUrl the whole code works and gives me 10 results like it should do:
JSONObject root = new JSONObject(jsonData);
JSONArray resultArray = root.getJSONObject("response").getJSONArray("results");
for(int i=0;i<resultArray.length();i++){
JSONObject resultElement = resultArray.getJSONObject(i);
/*
JSONObject blocksElement = resultElement.getJSONObject("blocks");
JSONObject mainElement = blocksElement.getJSONObject("main");
JSONArray elementsArray = mainElement.getJSONArray("elements");
JSONObject elementsElement = elementsArray.getJSONObject(0);
JSONArray assetsArray = elementsElement.getJSONArray("assets");
JSONObject assetsElement = assetsArray.getJSONObject(0);
String imageUrl = assetsElement.getString("file");
*/
String articleTitle = resultElement.getString("webTitle");
news.add(new NewsList(articleTitle, "test"));
}
I've looked around in Android monitor and it seems like it has a problem that says
org.json.JSONException: No value for main
But that is not correct as the URL for the first 3 result is found without any problem, the problem only occurs after 3 iterations of the loop and I can't find any reason for why this is happening.
Use everywhere "opt" instead of "get', e.g.:
JSONObject assetsElement = assetsArray.optJSONObject(0);
String imageUrl = assetsElement.optString("file");
this is happening because of there is no field "main" in the response at some position in the line
JSONObject mainElement = blocksElement.getJSONObject("main");
so if at any of the position any of the fields are missing from the response, then after that position the code will not compile in JSON parsing.
sorry for bad english .

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

How to parse objects in json?

I am trying to parse a json but it give me error java lang.string can not be converted to jsonArray. Here is my json and error :
Value {"MemberList":[{"MemberId":1,"FirmId":1,"MemberTypeId":1,
"MemberUserName":"test#example.com", "MemberName":"sth","UpdateDate":"\/Date(1421840040000)\/",
"LastLoginDate":"\/Date(1454995980000)\/",
"FirmTypeId":1,"FirmName":"Firm","FirmOfficialName":"Firm",
"FirmRowGuid":"sth","MemberRowGuid":"sth","AuthToken":"sth",
"IsRegistered":1}],"MemberPageList":null,"FirmModuleList":null,"Status":true,
"StatusCode":"OK"} of type java.lang.String cannot be converted to JSONArray
When i deleted MemberList header and run manually it works fine but i must parse it with header how should i parse it. userDetail is my json string:
JSONArray jsonArray = new JSONArray(userDetail);
member = new Member();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
member.MemberId = jsonObject.optInt("MemberId");
member.MemberTypeId = jsonObject.optInt("MemberTypeId");
member.FirmTypeId = jsonObject.optInt("FirmTypeId");
member.IsRegistered = jsonObject.optInt("IsRegistered");
member.MemberUserName = jsonObject.optString("MemberUserName");
member.MemberName = jsonObject.optString("MemberName");
member.UpdateDate = jsonObject.optString("UpdateDate");
member.LastLoginDate = jsonObject.optString("LastLoginDate");
member.FirmName = jsonObject.optString("FirmName");
member.FirmOfficialName = jsonObject.optString("FirmOfficialName");
member.FirmRowGuid = jsonObject.optString("FirmRowGuid");
member.MemberRowGuid = jsonObject.optString("MemberRowGuid");
member.AuthToken = jsonObject.optString("AuthToken");
}
Its a json object not array so change,
JSONArray jsonArray = new JSONArray(userDetail);
to
JSONObject jsonObj= new JSONObject(userDetail);
JSONArray jsonArray = jsonObj.getJSONArray("MemberList");
To manually check json use this http://jsoneditoronline.org/
CODE:
JSONObject jsonObj= new JSONObject(userDetail);
JSONArray jsonArray = jsonObj.getJSONArray("MemberList");
for (int i = 0; i < jsonArray.length(); i++) {
member = new Member();
JSONObject jsonObject = jsonArray.getJSONObject(i);
member.MemberId = jsonObject.optInt("MemberId");
member.MemberTypeId = jsonObject.optInt("MemberTypeId");
member.FirmTypeId = jsonObject.optInt("FirmTypeId");
member.IsRegistered = jsonObject.optInt("IsRegistered");
member.MemberUserName = jsonObject.optString("MemberUserName");
member.MemberName = jsonObject.optString("MemberName");
member.UpdateDate = jsonObject.optString("UpdateDate");
member.LastLoginDate = jsonObject.optString("LastLoginDate");
member.FirmName = jsonObject.optString("FirmName");
member.FirmOfficialName = jsonObject.optString("FirmOfficialName");
member.FirmRowGuid = jsonObject.optString("FirmRowGuid");
member.MemberRowGuid = jsonObject.optString("MemberRowGuid");
member.AuthToken = jsonObject.optString("AuthToken");
}
{
"MemberList": [{
"MemberId": 1,
"FirmId": 1,
"MemberTypeId": 1,
"MemberUserName": "test#example.com",
"MemberName": "sth",
"UpdateDate": "\/Date(1421840040000)\/",
"LastLoginDate": "\/Date(1454995980000)\/",
"FirmTypeId": 1,
"FirmName": "Firm",
"FirmOfficialName": "Firm",
"FirmRowGuid": "sth",
"MemberRowGuid": "sth",
"AuthToken": "sth",
"IsRegistered": 1
}],
"MemberPageList": null,
"FirmModuleList": null,
"Status": true,
"StatusCode": "OK"
}
as you can see the top root data we are getting as an object, within this object we are getting array of "MemberList", so you need to get object first then array inside of it.
and also do this to convert response in to String
HttpResponse response=client.execute(post);
String obj= EntityUtils.toString(response.getEntity());
then use it as you want.
Hope you got this.

Android json parsing without array name

I have a Json Array as string without name and I want to parse it how can i do it in android ?
My array :
{"emp_info":[
{"id":"1","groupe":"1","professeur":"1"},
{"id":"2","groupe":"2","professeur":"1"}
]}
This is how you can parse it
Assuming your json string is data
JSONObject jsonObj = new JSONObject(data);
JSONArray empInfo = jsonObj.getJSONArray("emp_info");
for(int i = 0; i < empInfo.length(); i++){
JSONObject obj = empInfo.getJSONObject(i);
String id = obj.getString("id");
String groupe = obj.getString("groupe");
String professeur = obj.getString("professeur");
}
The example json you gave has a name, but if it doesn't this is how I do it. Using Gson to parse JSON, I use TypeToken to tell the gson builder it's an array.
List<MyObject> jsonObject = new Gson().fromJson(json, new TypeToken<List<MyObject>>().getType());
With the following code you'll have an object representation of your json array.

Categories

Resources