Recover field Json 2 array level gson or Jackson - java

I have this Json and i can´t recover the field "entidad" and "oficina":
{
"resultado": [
{
"columa": [
"p"
],
"datos": [
{
"row": [
{
"oficina": "0000",
"entidad": "1234",
"nombre": "nombre persona"
}
],
"meta": [
{
"id": 4700925,
"type": "node",
"deleted": false
}
]
}
]
}
],
"errors": [],
"responseTime": 84
}
How can I recover the field "oficina" and "entidad"?
I could use Gson or Jackson.
I can´t recover this fields.
thank you

Get your array 'row'. When you got it, you can iterate it and extract the elements:
Get resultado --> get datos --> get row, then:
for(int i=0; i<arrayJSON.length; i++) {
JSONObject objectJSON= arrayJSON.get(i);
String entidad = objectJSON.getString("entidad");
String oficina = objectJSON.getString("oficina");
}

Related

How to fetch values from nested JSON in JAVA using Jsonpath

Below is the JSON response, I have used JSONPath get() to retrieve value of totalContractAmout by using below path - subscriptionQuoteResponseDetails.customerQuoteDetails[0].billPlanQuoteDetails[0].serviceList[0].skuList[0].totalContractAmount
But this seems to be hard coded, is there any way I can make it generic using JAVA language.
{
"transactionId": "Transaction123",
"systemId": "AAA",
"userId": "User123",
"resultDate": "2019-11-23T12:52:16.400-06:00",
"resultCode": "100",
"resultMessage": "SUCCESS",
"subscriptionQuoteResponseDetails": {
"quoteDetailsStatusCode": 2,
"customerQuoteDetails": [
{
"customerId": "546789",
"buid": "111",
"billPlanQuoteDetails": [
{
"serviceList": [
{
"serviceType": "/service/",
"skuList": [
{
"skuId": "932125",
"productName": "DummyName",
"quantity": 4,
"totalContractAmount": 1728,
"rateCards": [
{
"productCadence": "M",
"cadenceAmount": 48
},
{
"productCadence": "F",
"cadenceAmount": 1728
}
]
}
]
}
]
}
]
}
]
}
}

JSON to JSON Transform of input sample using any existing java library/tools

Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}

Parsing Json data giving ClassCastException

I am currently using the following JSON parser but keep getting the error Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject. How can I fix this, it has worked many times before.
ublic List<String> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<String> result = new ArrayList<String>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
// Get top-level JSON Object - a Map
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue(); //Problem Line
JSONObject item1 = responseObject.getJSONObject("searchResult");
// Extract value of "Item" key -- a List
JSONArray items = item1
.getJSONArray("Item");
Below is what I'm looking to parse
{
"findItemsAdvancedResponse":[
{
"ack":[
"Success"
],
"version":[
"1.13.0"
],
"timestamp":[
"2015-02-24T18:43:51.778Z"
],
"searchResult":[
{
"#count":"100",
"item":[
{
"itemId":[
"381098176861"
],
"title":[
" Tokyo Laundry Women's Kenzie Sweatpants - Eclipse Blue - TP1"
],
"globalId":[
"EBAY-GB"
],
"subtitle":[
"FREE UK DELIVERY | DISPATCHED WITHIN 1 WORKING DAY"
],
"primaryCategory":[
{
"categoryId":[
"137085"
],
"categoryName":[
"Activewear"
]
}
],
"secondaryCategory":[
{
"categoryId":[
"155226"
],
"categoryName":[
"Hoodies & Sweats"
]
}
],
"galleryURL":[
"http:\/\/thumbs2.ebaystatic.com\/pict\/3810981768614040_1.jpg"
],
"viewItemURL":[
"http:\/\/www.ebay.co.uk\/itm\/Tokyo-Laundry-Womens-Kenzie-Sweatpants-Eclipse-Blue-TP1-\/381098176861?pt=LH_DefaultDomain_3&var="
],
"paymentMethod":[
"PayPal"
],
"autoPay":[
"true"
],
"location":[
"United Kingdom"
],
"country":[
"GB"
],
"shippingInfo":[
{
"shippingServiceCost":[
{
"#currencyId":"GBP",
"__value__":"0.0"
}
],
"shippingType":[
"Free"
],
"shipToLocations":[
"AU",
"Europe"
]
}
],
"sellingStatus":[
{
"currentPrice":[
{
"#currencyId":"GBP",
"__value__":"14.99"
}
],
"convertedCurrentPrice":[
{
"#currencyId":"GBP",
"__value__":"14.99"
}
],
"sellingState":[
"Active"
],
"timeLeft":[
"P25DT14H10M23S"
]
}
],
"listingInfo":[
{
"bestOfferEnabled":[
"false"
],
"buyItNowAvailable":[
"false"
],
"startTime":[
"2014-12-22T08:49:14.000Z"
],
"endTime":[
"2015-03-22T08:54:14.000Z"
],
"listingType":[
"FixedPrice"
],
"gift":[
"false"
]
}
],
"galleryPlusPictureURL":[
"http:\/\/galleryplus.ebayimg.com\/ws\/web\/381098176861_1_1_1.jpg"
],
"condition":[
{
"conditionId":[
"1000"
],
"conditionDisplayName":[
"New with tags"
]
}
],
"isMultiVariationListing":[
"true"
],
"topRatedListing":[
"false"
]
},
{
"itemId":[
"131321072184"
],
"title":[
"Brave Soul Women's Dallas Parka - Mulberry - DD6 - Size 8-16"
],
"globalId":[
"EBAY-GB"
],
"subtitle":[
"FREE UK DELIVERY | DISPATCHED WITHIN 1 WORKING DAY"
],
"primaryCategory":[
{
"categoryId":[
"137085"
],
"categoryName":[
"Activewear"
]
}
],
"secondaryCategory":[
{
"categoryId":[
"63862"
],
"categoryName":[
"Coats & Jackets"
]
}
],
"galleryURL":[
"http:\/\/thumbs1.ebaystatic.com\/pict\/1313210721844040_3.jpg"
],
"viewItemURL":[
"http:\/\/www.ebay.co.uk\/itm\/Brave-Soul-Womens-Dallas-Parka-Mulberry-DD6-Size-8-16-\/131321072184?pt=LH_DefaultDomain_3&var="
],
"paymentMethod":[
"PayPal"
],
"autoPay":[
"true"
],
"location":[
"United Kingdom"
],
"country":[
"GB"
],
"shippingInfo":[
{
"shippingServiceCost":[
{
"#currencyId":"GBP",
"__value__":"0.0"
}
],
"shippingType":[
"Free"
],
"shipToLocations":[
"AU",
"Europe"
]
}
],
"sellingStatus":[
{
"currentPrice":[
{
"#currencyId":"GBP",
"__value__":"19.99"
}
],
"convertedCurrentPrice":[
{
"#currencyId":"GBP",
"__value__":"19.99"
}
],
"sellingState":[
"Active"
],
"timeLeft":[
"P15DT14H57M21S"
]
}
],
"listingInfo":[
{
"bestOfferEnabled":[
"false"
],
"buyItNowAvailable":[
"false"
],
"startTime":[
"2014-10-13T09:36:12.000Z"
],
"endTime":[
"2015-03-12T09:41:12.000Z"
],
"listingType":[
"FixedPrice"
],
"gift":[
"false"
]
}
],
"galleryPlusPictureURL":[
"http:\/\/galleryplus.ebayimg.com\/ws\/web\/131321072184_1_5_1.jpg"
],
"condition":[
{
"conditionId":[
"1000"
],
"conditionDisplayName":[
"New with tags"
]
}
],
"isMultiVariationListing":[
"true"
],
"topRatedListing":[
"false"
]
},
Why do you need a JSONTokener? This is much easier:
JSONObject responseObject = new JSONObject(JSONResponse);
JSONArray main = responseObject.getJSONArray("findItemsAdvancedResponse");
JSONObject result = main.getJSONObject(0).getJSONArray("searchResult").getJSONObject(0);
JSONArray items = result.getJSONArray("item");
Your nextValue() method must be returning a String, which you are then trying to cast to a JSONObject. I would start by splitting the statement up into smaller statements to help isolate the issue. You are instantiating a new object, calling a method on it, and type casting all on the same line. That makes code harder to debug.
JSONTokener tokener = new JSONTokener(JSONResponse);
Object obj = tokener.nextValue();
if(obj.getClass().equals(JSONObject.class))
{
JSONObject responseObject = (JSONObject)obj;
}
else
{
System.out.println("Not a JSONObject");
}

Get sub-array from JSON

I parsing some data from a json file. Here is my JSON File.
[
{
"topic": "Example1",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Presentation"
},
{
"topic": "Example2",
"contact": [
{
"ref": [
1
],
"corresponding": true,
"name": "XYZ"
},
{
"ref": [
1
],
"name": "ZXY"
},
{
"ref": [
1
],
"name": "ABC"
},
{
"ref": [
1,
2
],
"name":"BCA"
}
] ,
"type": "Poster"
}
]
I can fetch and store data one by one. Like this one
JSONArray getContactsArray = new JSONArray(jsonObject.getString("contact"));
for(int a =0 ; a < getContactsArray.length(); a++)
{
JSONObject getJSonObj = (JSONObject)getContactsArray.get(a);
String Name = getJSonObj.getString("name");
}
1)Now, my question is there any way to get all name values for each array with single query.
2) Can I get all those values in an Array ?
Please correct me, if I am doing anything wrong. Thank you.
Iteration cannot be avoided here as org.json and other Json parsers as well provide random access to objects but not to their properties collectively (as a collection). So, you can't query something like "all name properties of all contact objects" unless you probably get a Json parser like Gson to unmarshall it that way.
But, that's too much to just avoid a for loop when you can definitely shorten the parse by making use of the appropriate API methods to avoid unnecessary object casts.
JSONArray contacts = jsonObject.getJSONArray("contact");
String[] contactNames = new String[contacts.length()];
for(int i = 0 ; i < contactNames.length; i++) {
contactNames[i] = contacts.getJSONObject(i).getString("name");
}
Better to use a json parser such as GSon or Jackson to marshall your json to a java object. Then you can write utitlity method in your java class to retrieve all the names in that object.
Try this:
Create JSONObject of your file and try to get array of all names and iterate it to get all values.
public static String[] getNames(JSONObject jo) {
int length = jo.length();
if (length == 0) {
return null;
}
Iterator i = jo.keys();
String[] names = new String[length];
int j = 0;
while (i.hasNext()) {
names[j] = (String) i.next();
j += 1;
}
return names;
}

Json Gson not working (Exception object / String)

i have a problem of transfer JSON to java type, I want to transfer this JSON:
{ "kind": "fusiontables#sqlresponse", "columns": [ "Pre", "Post" ], "rows": [ [ "Si2", "Si2" ], [ "CeSP-A", "CeSP-A" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ] ]}
to a java list which each one of the list has two private string Pre and Post
Here is my code:
Gson gson = new Gson();
List<Edges> list = gson.fromJson(jsonU,
new TypeToken<List<Edges>>() {
}.getType());
for (int i = 0; i < list.size(); i++) {
Edges p = list.get(i);
System.out.println(p.getPre() + ", " + p.getPost());
System.out.println();
}
and
jsonU is the String of JSON file
{ "kind": "fusiontables#sqlresponse", "columns": [ "Pre", "Post" ], "rows": [ [ "Si2", "Si2" ], [ "CeSP-A", "CeSP-A" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ], [ "Si2", "Si1" ], [ "Si1", "Si2" ] ]}
However, i got the error:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
can you please help me resolve this problem? Thank you very much
You are telling GSON to deserialize a List<Edges> yet the JSON you are passing starts with an object, with the { and } tokens.
GSON, based on the type parameters you've passed to it, is expecting something like:
[
{ "kind": .... },
{ "kind: .... },
...
]
In other words, how can GSON construct a List of something when you are passing it JSON corresponding to a single object?

Categories