Dynamic JSON Model - java

Here, I'm trying to parse this JSON Object into model. But I'm stuck here with the dynamic field names. Here is the example of the JSON Object
{
"1": {
"state": {
"on": false,
"bri": 0,
"hue": 0,
"sat": 0,
"effect": "none",
"xy": [
0,
0
],
"ct": 0,
"alert": "none",
"colormode": "hs",
"reachable": false
},
"type": "Extended color light",
"name": "Hue Lamp 1",
"modelid": "LCT001",
"manufacturername": "Philips",
"uniqueid": "00:17:88:01:00:f4:5a:aa-0b",
"swversion": "5.23.1.13452"
},
"2": {
"state": {
"on": false,
"bri": 254,
"hue": 8000,
"sat": 200,
"effect": "none",
"xy": [
0.5469,
0.3819
],
"ct": 500,
"alert": "none",
"colormode": "hs",
"reachable": true
},
"type": "Extended color light",
"name": "Hue Lamp 2",
"modelid": "LCT001",
"manufacturername": "Philips",
"uniqueid": "00:17:88:01:00:f4:5c:55-0b",
"swversion": "5.23.1.13452"
}
}
There are these field "1","2" and so on. How to parse this into model ? Can anybody help ?
Updated :
All i want to achieve is getting this "1", "2" key value and the "name" field value in it. Thanks before !

You need to wrap json in one root element then use model like this
public class RootElement{
private Map<String, DataInfo> rootElement;
}
public class DataInfo {
private State state= null;
private String type= null;
// all your field under 1, 2
}
And your json should look like this
"rootElement": {
"1": {
"state": {
"on": false,
"bri": 0,
"hue": 0,
"sat": 0,
"effect": "none",
"xy": [
0,
0
],
"ct": 0,
"alert": "none",
"colormode": "hs",
"reachable": false
},
"type": "Extended color light",
"name": "Hue Lamp 1",
"modelid": "LCT001",
"manufacturername": "Philips",
"uniqueid": "00:17:88:01:00:f4:5a:aa-0b",
"swversion": "5.23.1.13452"
},
// other object
}

#tommy wu , try this
JSONObject questionMark = new JSONObject("your string containing whole json object");
Iterator keys = questionMark.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);
// do something here with the value...
}

Related

JSON Object Navigation to nested value

I am new to JSON and trying to manipulate JSON for some validation
My JSON looks like this . I need to pick the JSON object based on the refcode and then get count of different object in that, and navigate deeper inside to get the key value pair. Can someone guide me how I can navigate.
{
"components": [
{
"id": 12,
"text": "ABC",
"refCode": "CO_ABC",
"patternCode": "0",
"components": [
{
"id": 1234,
"text": "types",
"refCode": "CO_TYPES",
"questions": [
{
"questionId": 122324,
"questionText": "Is this you",
"questionSequence": 1,
"questionRefCode": "QN_STAY",
"hasPreselectedAnswer": false,
"responsesMetadata": {
"cardinality": "single",
"patternCode": "5",
"dataType": "STRING",
"numberMin": null,
"numberMax": null
},
"choices": [
{
"choiceId": 5456,
"choiceRefCode": "YES",
"choiceText": "Yes",
"sequence": 1
},
{
"choiceId": 8798,
"choiceRefCode": "NO",
"choiceText": "No",
"sequence": 2
}
],
"editable": true,
"accessible": true
}
]
},
{
"id": 13,
"text": "State of stay",
"refCode": "CO_STATE",
"questions": [
{
"questionId": 1,
"questionText": "Which state do you stay",
"questionSequence": 2,
"questionRefCode": "QN_STATE",
"hasPreselectedAnswer": false,
"responsesMetadata": {
"cardinality": "multiple",
"patternCode": "1",
"dataType": "STRING",
"numberMin": null,
"numberMax": null
},
"choices": [
{
"choiceId": 1,
"choiceRefCode": "CH_AZ",
"choiceText": "Arizona",
"sequence": 1
},
{
"choiceId": 2,
"choiceRefCode": "CH_PA",
"choiceText": "Pennsylvania",
"sequence": 2
}
],
"accessible": true
}
]
}
]
}
]
}

getting array of ids , but need to get String

I,m testing API with rest assured , and trying to get Id's from my created product as a String with the following method below
String productId = response.jsonPath().getString("productPrices.productId");
String channelId = response.jsonPath().getString("productPrices.channelId");
but it's returning me an array
when I print out those Ids, the following output is being got;
System.out.println("productId is ===> " +productId);
System.out.println("channelId is ===> " +channelId);
Output is
productId is ===>[jpjeneOM]
channelId is ===>[5bpJKaVE]
My issue is , i need to get those Ids as a String only !!!
pls help me to resolve this issue
thanks in advance
And I have the following payload
{
"id": "jpjeneOM",
"name": "NewProductForTest",
"productTypeId": null,
"active": true,
"shortDescription": "API",
"fullDescription": "API Automation",
"policy": null,
"mostPopular": null,
"longitude": 34.774667,
"latitude": 32.085814,
"calendarColor": "blue",
"address": "Dizengoff Street, Tel Aviv-Yafo",
"cityId": "nlYxZ6az",
"createdAt": "2021-08-06T07:49:14.920615",
"productImages": [
],
"productDocuments": [
],
"productTypes": null,
"productWorkingDates": [
{
"id": "baQkKROA",
"productId": "jpjeneOM",
"fromDate": "2021-05-27",
"toDate": "2022-12-31",
"name": "StrickHours",
"strictHours": true,
"timeSlots": [
{
"id": "1lkvdZa6",
"productWorkingDateId": "baQkKROA",
"dayOfWeek": "Monday",
"startTime": "09:00:00",
"endTime": "20:00:00",
"duration": "01:00:00",
"quantity": 67,
"usedQuantity": 0,
"active": true,
"deletedAt": null
}
],
"deletedAt": null,
"maxUsedTicketsQuantity": 0,
"errorCode": 0
}
],
"productRegions": [
{
"id": "4lrWZgOd",
"productId": "jpjeneOM",
"regionId": "5bpJKaVE",
"regionName": null
}
],
"productPrices": [
{
"id": "1lon0Aa7",
"productId": "jpjeneOM",
"channelId": "5bpJKaVE",
"fromDate": "2021-08-02T00:00:00",
"toDate": "2022-12-31T00:00:00",
"title": "API",
"remarks": "Test",
"officialPrice": 34,
"currencyId": "5bpJKaVE",
"quantityPerDay": 123,
"autoConfirm": true,
"pricePerPerson": false,
"productPriceTypes": [
{
"id": "xl4WJ7aj",
"productPriceId": "1lon0Aa7",
"productCustomerTypeId": "ZOw36ZOx",
"amount": 12,
"currencyId": "5bpJKaVE",
"currencySymbol": null,
"isOfficial": false,
"productCustomerType": null
}
],
"deletedAt": null
}
]
The productPrices in example is an array, and you didn't mention which one to choose, the jsonpath syntax is like productPrices.*.channelId, so you get arrays. You can choose the first one like productPrices.0.channelId or else.

JAVA: How to find all matches of a substring in a nested JSONString and replace with some text

JSON String looks like
{
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500,
"stamp" : "randomtestcasenumberwithtimeID2",
"case" : 1
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"stamp" : "randomtestcasenumberwithtimeID3"
},
}
}
I want to replace all instances of "stamp" with something static such "stamp" : "Testing". How would I go about this? please note the value of "stamp" is random.
So after the search and replace both instance of stamp should have same value "Testing" Example
{
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500,
"stamp" : "Testing",
"case" : 1
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"stamp" : "Testing"
},
}
}
You can try this:
String json = "<your-json-here>";
String newValue = "Testing";
String newJson = s.replaceAll("\"stamp\"\\s*:\\s*\"(.*)\"", String.format("\"stamp\" : \"%s\"", newValue));
or even something like this:
String s2 = s.replaceAll("(?<=\"stamp\")\\s*:\\s*\"(.*)(?=\")", ":\""+ newValue);

Can't access variable in JSON

I'm having trouble with my JSONObject
this is my code :
importPackage(Packages.org.apache.commons.io);
importPackage(Packages.java.io);
fisTargetFile = new FileInputStream(new File("C:/moe.json"));
input = IOUtils.toString(fisTargetFile, "UTF-8");
jsonData = input;
myJSONObject = eval('(' + jsonData + ' )');
len = myJSONObject.cells.length;
count = 0;
if (count < len) {
var name = myJSONObject.cells[count].attrs.text;
var type = myJSONObject.cells[count].type;
var photo = myJSONObject.cells[count].attrs.image.xlink:href;
row["name"] = name;
row["type"] = type;
// row["photo"] = photo;
count++;
return true;
}
return false;
My problem is in this line var photo = myJSONObject.cells[count].attrs.image.xlink:href;
i can't access my Image data because this is not a correct syntax ":" how can i overcome it ? is there a way to escape the ":" ?
Edit :
this is my JSON object :
{
"cells": [
{
"type": "basic.Platform",
"size": {
"width": 60,
"height": 60
},
"custom": {
"identifier": [
{
"name": "Name1",
"URI": "Value1"
}
],
"classifier": [
{
"name": "Name2",
"URI": "Value2"
}
],
"output": [
{
"name": "Name3",
"URI": "Value3"
}
],
"imported": false,
"event": [
]
},
"ref": [
],
"uuid": [
"dc537ba7-b9dc-476e-9f09-8c1f5211f9bb"
],
"position": {
"x": 390,
"y": 230
},
"angle": 0,
"id": "dc537ba7-b9dc-476e-9f09-8c1f5211f9bb",
"embeds": "",
"z": 1,
"description": "",
"attrs": {
"text": {
"font-size": "9",
"text": "rere",
"ref-x": "0.5",
"ref-dy": "20",
"fill": "#000000",
"font-family": "Arial",
"display": "",
"stroke": "#000000",
"stroke-width": "0",
"font-weight": "400"
},
"image": {
"width": 50,
"height": 50,
"xlink:href": "data:image\/png;base64,iVBORw0KGgoAAAANSUhEUgAAAG4AAACWCAYAAAA\/mr2PAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS5EOsBjwfqm3fvx0eIfsT89"
}
}
}
]
}
I have trimmed the xlink:href data because it's too long.
Yes there is
myJSONObject.cells[count].attrs.image["xlink:href"]
Reasoning: Any where you use the dot notation to separate object references you can also use the square bracket notation and pass in a string. This is the standard way to reference something that is not a "valid" identifier such as a colon in the middle of a name.
In JavaScript, objects are also associative arrays (or hashes).
That is, the property foo.bar can also be read or written by calling foo["bar"]
var photo = myJSONObject.cells[count].attrs.image["xlink:href"];
You may try to access it like a property of image["xlink:href"].
Or please specify what that column stands for.

How can I parse this JSON in Android?

I want to pull out the user block. The JSON result will always change, sometimes 4 users will be returned, sometimes 10 etc.
{
"results": [
{
"user": {
"avatar_url_thumb": "http://avatars.stocktwits.com/production/9998/thumb-1270014645.png?1270014645",
"avatar_url_medium": "http://avatars.stocktwits.com/production/9998/medium-1270014645.png?1270014645",
"created_at": "2010-03-15T05:44:51Z",
"following_count": 14,
"updated_at": "2010-08-30T18:22:15Z",
"id": 9998,
"updates_count": 31,
"avatar_url_large": "http://avatars.stocktwits.com/production/9998/large-1270014645.png?1270014645",
"investor_relations": false,
"last_name": "Reporter",
"followers_count": 25,
"recommended": false,
"bio": "Apple News & AAPL Stock Analysis, visit Apple Digest blog link above",
"login": "AppleReporter",
"first_name": "Apple"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-04-14T01:02:05Z",
"following_count": 0,
"updated_at": "2010-08-30T18:29:56Z",
"id": 12924,
"updates_count": 1,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "Shareholder",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "Imurphit",
"first_name": "Apple"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-04-17T20:52:09Z",
"following_count": 0,
"updated_at": "2010-08-30T18:31:23Z",
"id": 13234,
"updates_count": 0,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "Apple",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "apple11",
"first_name": "John"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-07-12T19:04:51Z",
"following_count": 0,
"updated_at": "2010-08-30T20:12:15Z",
"id": 18691,
"updates_count": 0,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "Smith",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "apple",
"first_name": "Jacob"
}
},
{
"user": {
"avatar_url_thumb": "http://api.stocktwits.com/images/default_avatar_thumb.jpg",
"avatar_url_medium": "http://api.stocktwits.com/images/default_avatar_medium.jpg",
"created_at": "2010-07-13T17:06:27Z",
"following_count": 0,
"updated_at": "2010-08-30T20:12:30Z",
"id": 18808,
"updates_count": 3,
"avatar_url_large": "http://api.stocktwits.com/images/default_avatar_large.jpg",
"investor_relations": false,
"last_name": "apple",
"followers_count": 0,
"recommended": false,
"bio": null,
"login": "applejames",
"first_name": "James"
}
}
],
"page": 1,
"symbol": false,
"per_page": 20,
"response": {
"status": 200
},
"total_pages": 1,
"total_entries": 6
}
Use the JSONObject
// Get some JSON from wherever
String json = getJSONFromServer();
// Parse the JSON response into an object
JSONObject object = new JSONObject(json);
// Get the results array
JSONArray users = object.getJSONArray("results");
for(int i = 0; i < users.length(); i++) {
// Each element in the results array is a JSONObject with a single
// property "user" which is a JSONObject that contains the user data
JSONObject user = users.getJSONObject(i).getJSONObject("user");
// Do something with the user
String firstName = user.getString("first_name");
}

Categories

Resources