Java JsonPath length of array - java

I have a Json like this:
{
"hello": {
"hello": [
{
"wwrjgn": "aerg",
"aaa": "gggg",
"rfshs": {
"segse": "segsegs",
"xx": "rgwgwgw",
"x-e ": "eergye"
},
"egg": "sgsese",
"segess": "sgeses",
"segess": "segess"
},
{
"esges": "segesse",
"segesg": "ws",
"rddgdr": {
"rdrdrdg": “srgsesees"
},
"drr": 3600,
"esese": "uytk",
"wew": "699",
"eses": “qe4ty"
}
],
"how": www"
}
}
I do the following:
Object document =
Configuration.defaultConfiguration().addOptions().jsonProvider()
.parse(ka.toJSONString());
int queries = JsonPath.read(document, "$..hello.length()");
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + queries);
I get:
nested exception is java.lang.ClassCastException: net.minidev.json.JSONArray
cannot be cast to java.base/java.lang.Integer] with root cause
java.lang.ClassCastException: net.minidev.json.JSONArray cannot be cast to
java.base/java.lang.Integer
Trying it here: http://jsonpath.herokuapp.com/?path=$..hello.length()
I get:
[
2,
2
]
Which is what i need.
Any idea what i am doing wrong?
Thanks in advance.

This ...
JsonPath.read(document, "$..hello.length()")
... will cast its response an instance of net.minidev.json.JSONArray which cannot be cast to an int. This explains the ClassCastException
The reason you see ...
[
2,
2
]
... when trying the online evaulator is that this is the toString() for the JSONArray instance returns that String.
To get the "THE LENGTH OF THE NUMBER OF QUERIES " in code, just read the JsonPath output as a JSONArray and then get the size attribute of that type. For example:
JSONArray read = JsonPath.read(document, "$..hello.length()");
// prints:
// THE LENGTH OF THE NUMBER OF QUERIES 2
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + read.size());
You could also return a List<Integer, for example:
List<Integer> read = JsonPath.read(document, "$..hello.length()");
// prints:
// THE LENGTH OF THE NUMBER OF QUERIES 2
System.out.println("THE LENGTH OF THE NUMBER OF QUERIES " + read.size());

Related

JSON array getting last index instead of its sequence

Hi I am using json parsing, I am getting json response from backend and parsing is working well. but the issue is that when I try to set data as per response it sets last index only. Following is my snippet code and json response can any one help me with this please.
Right now it shows output
(in my first textview)
Buy 12 Canex + 1 Dose Free
(in my second textview)
Buy 12 Canex + 1 Dose Free
{
"Data": {
"shippingText": "heyy",
"productOffersList": [
{
"bgColorA": "#ffffff",
"bgColorI": "255*255*255",
"offerLine": [
{
"text": "BUY 6",
"colorA": "#82d7ff",
"colorI": "130*215*255"
},
{
"text": " Canex + 1 Dose Free",
"colorA": "#ff8282",
"colorI": "255*130*130"
}
]
},
{
"bgColorA": "#ffffff",
"bgColorI": "255*255*255",
"offerLine": [
{
"text": "BUY 12",
"colorA": "#65dd63",
"colorI": "101*221*99"
},
{
"text": " Canex + 1 Dose Free",
"colorA": "#ff8282",
"colorI": "255*130*130"
}
]
}
]
},
"Status": 1,
"Message": "",
"UserMessage": ""
}
Code
JSONArray productOffersList=drawerdatas.getJSONArray("productOffersList");
for(int k=0;k<productOffersList.length();k++)
{
JSONObject joofer = productOffersList.getJSONObject(k);
JSONArray offerLine=joofer.getJSONArray("offerLine");
offertextlist=new ArrayList<ProductOffersModel>();
for(int l=0;l<offerLine.length();l++)
{
JSONObject jooferline = offerLine.getJSONObject(l);
ProductOffersModel pom=new ProductOffersModel();
pom.setProductOffers_text(jooferline.getString("text"));
pom.setProductOffers_colorA(jooferline.getString("colorA"));
offertextlist.add(pom);
}
}
for(int v=0;v<offertextlist.size();v++)
{
product_view_offertextfirst.setText(offertextlist.get(v).getProductOffers_text()+" "+offertextlist.get(v).getProductOffers_text());
}
for(int v=0;v<offertextlist.size();v++)
{
product_view_offertexttwo.setText(offertextlist.get(v).getProductOffers_text()+" "+offertextlist.get(v).getProductOffers_text());
}
because you are doing a for loop to set the text of the textviews you are setting on both all the offers and the last one is what you are able to see
JSONArray productOffersList=drawerdatas.getJSONArray("productOffersList");
offertextlist=new ArrayList<ProductOffersModel>();
// You were re creating the list array list inside the for loop so you were losing the data from the 1st product.
for(int k=0;k<productOffersList.length();k++)
{
JSONObject joofer = productOffersList.getJSONObject(k);
JSONArray offerLine=joofer.getJSONArray("offerLine");
for(int l=0;l<offerLine.length();l++)
{
JSONObject jooferline = offerLine.getJSONObject(l);
ProductOffersModel pom=new ProductOffersModel();
pom.setProductOffers_text(jooferline.getString("text"));
pom.setProductOffers_colorA(jooferline.getString("colorA"));
offertextlist.add(pom);
}
}
if(offertextlist !=null && offertextlist.size()==4)
{
product_view_offertextfirst.setText(offertextlist.get(0).getProductOffers_text()
+ " " + offertextlist.get(1).getProductOffers_text());
product_view_offertexttwo.setText(offertextlist.get(2).getProductOffers_text()
+ " " + offertextlist.get(3).getProductOffers_text());
}
try with this parsing,
JSONArray productOffersList=drawerdatas.getJSONArray("productOffersList");
for(int k=0;k<productOffersList.length();k++)
{
JSONObject joofer = productOffersList.getJSONObject(k);
JSONArray offerLine=joofer.getJSONArray("offerLine");
offertextlist=new ArrayList<ProductOffersModel>();
ProductOffersModel pom=new ProductOffersModel();
pom.setProductOffers_text
(offerLine.getJSONObject(0).getString("text")+""+
offerLine.getJSONObject(1).getString("text"));
offertextlist.add(pom);
}
for(int v=0;v<offertextlist.size();v++)
{
if(v==0)
{
product_view_offertextfirst.setText
(offertextlist.get(v).getProductOffers_text());
}
else if(v==1)
{
product_view_offertexttwo.setText(
offertextlist.get(v).getProductOffers_text());
}
}
Handling JSON data manually is not a recommended practice for large datasets. You should go with a JSON parsing library, Gson may be a good choice.
https://github.com/google/gson

Why do I always get JSON Exception?

This Is my first time with parsing JSON data. I am using the Google knowledge graph api. I got the api working and I can get the JSON result. This is Google 's sample return data for a sample query which I'm using now for testing.
{
"#context": {
"#vocab": "http://schema.org/",
"goog": "http://schema.googleapis.com/",
"resultScore": "goog:resultScore",
"detailedDescription": "goog:detailedDescription",
"EntitySearchResult": "goog:EntitySearchResult",
"kg": "http://g.co/kg"
},
"#type": "ItemList",
"itemListElement": [
{
"#type": "EntitySearchResult",
"result": {
"#id": "kg:/m/0dl567",
"name": "Taylor Swift",
"#type": [
"Thing",
"Person"
],
"description": "Singer-songwriter",
"image": {
"contentUrl": "https://t1.gstatic.com/images?q=tbn:ANd9GcQmVDAhjhWnN2OWys2ZMO3PGAhupp5tN2LwF_BJmiHgi19hf8Ku",
"url": "https://en.wikipedia.org/wiki/Taylor_Swift",
"license": "http://creativecommons.org/licenses/by-sa/2.0"
},
"detailedDescription": {
"articleBody": "Taylor Alison Swift is an American singer-songwriter and actress. Raised in Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the age of 14 to pursue a career in country music. ",
"url": "http://en.wikipedia.org/wiki/Taylor_Swift",
"license": "https://en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License"
},
"url": "http://taylorswift.com/"
},
"resultScore": 896.576599
}
]
}
So I want to parse it so that I can get the name, description, detailed description. This is my code but I always seem to get the exception. Any ideas why?
try {
JSONObject object=new JSONObject(gggg);
JSONArray itemListElement = object.getJSONArray("itemListElement");
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name").toString();
String description = results.getString("description").toString();
String detailedDescription = results.getString("articleBody").toString();
gggg = "Name: "+name+"\n Description: "+description+"\n "+detailedDescription;
}
responseView.append(gggg);
} catch (JSONException e) {
Toast.makeText(MainActivity.this,gggg,Toast.LENGTH_LONG).show();
}
Also the string gggg contains the JSON data. I don't know why but I am always getting the exception. Please tell me what is the error in my code and how to repair it.
Thanks.
"Name: Taylor Swift Description: Singer-songwriter Taylor Alison
Swift is an American singer-songwriter and actress. Raised in
Wyomissing, Pennsylvania, she moved to Nashville, Tennessee, at the
age of 14 to pursue a career in country music. "
The problem is your String detailedDescription line.
You need to get the detailedDescription object before you retrieve the articleBody.
for(int i=0; i < itemListElement.length();i++){
JSONObject c = itemListElement.getJSONObject(i);
JSONObject results = c.getJSONObject("result");
String name = results.getString("name");
String description = results.getString("description");
JSONObject detailedDescription = results.getJSONObject("detailedDescription");
String articleBody = detailedDescription.getString("articleBody");
String x = "Name: "+name+"\n Description: "+description+"\n "+articleBody;
}
Also your .toString() method calls are redundant as you are calling .getString() on the JSON object.
With in the android json library it has a method called has element, which returns true or false. After successfully checking then access the element. The expection be caused by tring to access an element that isn't there.
Might be worth printing out after each time you create a new object to ensure that the objects are being created. It will also piont to where the expection is happening.

JSON Parsing Nested Array Objects

Using Simple-JSON on the following JSON formatted file, I'm having a lot of trouble understanding how to access the objects within the array under "name".
JSON File:
[
{
"name":{
"firstName": "Developer",
"lastName": "D"
},
"id": 00,
"permissionLevel": 3,
"password": 12345
},
{
"name":{
"firstName": "Bob",
"lastName": "Smith"
},
"id": 01,
"permissionLevel": 2,
"password": 23456
}
]
I'm able to obtain the information for all of the other contents because they're not located in a nested array; However, when I attempt to retrieve the objects under "name", all that is output is the String found in the JSON file.
Current code:
String[] searchData = {
"name",
"firstName",
"lastName",
"id",
"permissionLevel",
"password"
};
jsonArray = (JSONArray)new JSONParser().parse(s);
for(int i = 0; i < jsonArray.size(); i++){
JSONObject jo = (JSONObject)jsonArray.get(i);
for(int j = 0; j < searchData.length; j++){
System.out.println(
searchData[j] + ": " + jo.get(searchData[j]));
}
}
Output:
name: [{"firstName":"Developer","lastName":"D"}]
firstName: null
lastName: null
id: 0
permissionLevel: 3
password: 12345
name: [{"firstName":"Bob","lastName":"Smith"}]
firstName: null
lastName: null
id: 1
permissionLevel: 2
password: 23456
As you can see, "name" outputs a String from the JSON file, and not each individual value.
In the end, I need to write a universal code that can accept new "searchData" tags for each file that's input.
Might someone be able to direct me how to obtain objects held
within nested arrays?
Or perhaps I need to use a different Library? If so, which one is the most efficient for Java? I'm not programming for Android, and I continue to find Library suggestions for Android, constantly.
My apologies if this post is a dupe, but no other posts are aiding me.
You should get your firstname and lastname, like:
jo.get("name").get("firstname");
jo.get("name").get("lastname");
To get the objects held within nested arrays/objects, you will have to write a recursive method and flatten the structure into a map. Below example shows the same:
public static void main(String args[]) throws ParseException {
Object object = new JSONParser().parse("[ { \"name\":{ \"firstName\": \"Developer\", \"lastName\": \"D\" }, \"id\": 00, \"permissionLevel\": 3, \"password\": 12345 }, { \"name\":{ \"firstName\": \"Bob\", \"lastName\": \"Smith\" }, \"id\":01, \"permissionLevel\": 2, \"password\": 23456 }]");
Map<String, Object> pairs = new HashMap<>();
addValues(object, pairs);
System.out.println(pairs);
}
public static void addValues(Object object, Map<String, Object> pairs){
if(object instanceof JSONObject){
JSONObject jsonObject = (JSONObject) object;
for(String key : jsonObject.keySet()){
if(jsonObject.get(key) instanceof JSONObject || jsonObject.get(key) instanceof JSONArray){
addValues(jsonObject.get(key), pairs);
}else{
pairs.put(key, jsonObject.get(key));
}
}
}else if(object instanceof JSONArray){
JSONArray jsonArray = (JSONArray)object;
for(Object element : jsonArray){
addValues(element, pairs);
}
}
}
You can tweak this method to have keys like name.firstname or name.lastname depending on requirements.
I understand that you want the searchData tags to be taken into consideration while parsing the JSON. I would suggest using Google Gson for this case.
You can write a POJO which return the ArrayList<User> for your JSON.
Refer this article on how use Google Gson

GSON : How to convert Object (which itself contains JSON) to JSON

I have a different use case where fields in POJO itself stores JSON data, basically grouping of all data.
Now i want the complete JSON generated from above POJO.
At present i am using this method
private static Gson gson = new Gson();
public static String convertObjectToJSON(Object object) throws Exception {
String jsonResponse = gson.toJson(object);
return jsonResponse;
}
But getting output with escape characters around double quotes like below
{ \"_id\" : 234242, \"name\" : \"carlos\"}
I tried various options in GsonBuilder, but not working.
Basically, i am just grouping multiple JSON data and sending it across.
Could you please do the needful help to get rid of the escape characters around double quotes.
UPDATE:
Question is : I have 3 JSONs and need to combine them into a single JSON and need to pass it to html5 client through Spring MVC. As of now i am added the 3 JSONs into a POJO and trying to convert the same to JSON. Same is explained above.
Thanks & Regards
Venkat
I have tried below sample code and it doesn't have any escape characters around double quotes.
class MyPOJO{
private int _id;
private String name;
// getter & setter
}
String json="{ \"_id\" : 234242, \"name\" : \"carlos\"}";
MyPOJOobj=new Gson().fromJson(json, MyPOJO.class);
System.out.println(new Gson().toJson(obj));
output:
{"_id":234242,"name":"carlos"}
EDIT
If you want to combine 3 JSON string then It will be stored as List of object as illustrated below:
sample code:
String json = "[" +
" { \"_id\" : 1, \"name\" : \"A\"}," +
" { \"_id\" : 2, \"name\" : \"B\"}," +
" { \"_id\" : 3, \"name\" : \"C\"}" +
"]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
output:
[
{
"_id": 1,
"name": "A"
},
{
"_id": 2,
"name": "B"
},
{
"_id": 3,
"name": "C"
}
]

Parsing JSON data in Java for Android

I hope someone might be able to help me.
I am trying to parse following json file:
{"seminar":[
{"categoryid": "1","cpe": "13","inventory":["Discussion","Value x","Value y"
],"teachers": [
{
"titel": "Dipl.-Ing.",
"company": "XY",
"name": "Test",
"id": "3",
}
],
},...
I am lost with parsing the teachers data in...
...
private static final String TAG_teachers = "teachers";
private static final String TAG_TITLE = "title";
for(int i = 0; i < seminar.length(); i++){
JSONObject c = seminar.getJSONObject(i);
...
teachers = c.getJSONArray(TAG_DOZENTEN);
for(int z = 0; z < teachers.length(); z++){
JSONObject d = teachers.getJSONObject(z);
String title = d.getString(TAG_TITLE);
Log.d("JSONParsingActivity", title);
I get the error System.err(1010): org.json.JSONException: Value null
at teachers of type org.json.JSONObject$1 cannot be converted to
JSONArray.
What did I do wrong? As I understand from the JSON documentation, teachers is an JSON Array and not an Object. Is somebody able to help me?
You have an extra (trailing) comma in teachers (after "3"). Not allowed in JSON. Remove it and see if that helps.
If your JSON is really of the form:
{ ... }, { ... }, { ... }, ...
This is invalid JSON
The root enclosure must either be a single object (in {}) or an array (in []).
If your intent is to send an array of objects, then simply wrap the entire thing with square brackets to make it an array and create a JSONArray object from it.
So it must be like this
[ { ... }, { ... }, { ... }, ... ]
You also need to make sure that you don;t have extra commas, unclosed brackets, etc. Use JSONLint or other similar JSON format checker to save yourself some time in finding syntax problems.

Categories