Reading value of nested key in JSON with Java (Jackson) - java

I'm a new Java programmer coming from a background in Python. I have weather data that's being collected/returned as a JSON with nested keys in it, and I don't understand how pull the values out in this situation. I'm sure this question has been asked before, but I swear I've Googled a great deal and I can't seem to find an answer. Right now I'm using json-simple, but I tried switching to Jackson and still couldn't figure out how to do this. Since Jackson/Gson seem to be the most used libraries, I'd would love to see an example using one of those libraries. Below is a sample of the data, followed by the code I've written so far.
{
"response": {
"features": {
"history": 1
}
},
"history": {
"date": {
"pretty": "April 13, 2010",
"year": "2010",
"mon": "04",
"mday": "13",
"hour": "12",
"min": "00",
"tzname": "America/Los_Angeles"
},
...
}
}
Main function
public class Tester {
public static void main(String args[]) throws MalformedURLException, IOException, ParseException {
WundergroundAPI wu = new WundergroundAPI("*******60fedd095");
JSONObject json = wu.historical("San_Francisco", "CA", "20100413");
System.out.println(json.toString());
System.out.println();
//This only returns 1 level. Further .get() calls throw an exception
System.out.println(json.get("history"));
}
}
The function 'historical' calls another function that returns a JSONObject
public static JSONObject readJsonFromUrl(URL url) throws MalformedURLException, IOException, ParseException {
InputStream inputStream = url.openStream();
try {
JSONParser parser = new JSONParser();
BufferedReader buffReader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
String jsonText = readAll(buffReader);
JSONObject json = (JSONObject) parser.parse(jsonText);
return json;
} finally {
inputStream.close();
}
}

With Jackson's tree model (JsonNode), you have both "literal" accessor methods ('get'), which returns null for missing value, and "safe" accessors ('path'), which allow you to traverse "missing" nodes. So, for example:
JsonNode root = mapper.readTree(inputSource);
int h = root.path("response").path("history").getValueAsInt();
which would return the value at given path, or, if path is missing, 0 (default value)
But more conveniently, you can just use JSON pointer expression:
int h = root.at("/response/history").getValueAsInt();
There are other ways too, and often it is more convenient to actually model your structure as Plain Old Java Object (POJO).
Your content could fit something like:
public class Wrapper {
public Response response;
}
public class Response {
public Map<String,Integer> features; // or maybe Map<String,Object>
public List<HistoryItem> history;
}
public class HistoryItem {
public MyDate date; // or just Map<String,String>
// ... and so forth
}
and if so, you would traverse resulting objects just like any Java objects.

Use Jsonpath
Integer h = JsonPath.parse(json).read("$.response.repository.history", Integer.class);

Check out Jackson's ObjectMapper. You can create a class to model your JSON then use ObjectMapper's readValue method to 'deserialize' your JSON String into an instance of your model class. And vice-versa.

Try jpath API. It's xpath equivalent for JSON Data. You can read data by providing the jpath which will traverse the JSON data and return the requested value.
This Java class is the implementation as well as it has example codes on how to call the APIs.
https://github.com/satyapaul/jpath/blob/master/JSONDataReader.java
Readme -
https://github.com/satyapaul/jpath/blob/master/README.md
Example:
JSON Data:
{
"data": [{
"id": "13652355666_10154605514815667",
"uid": "442637379090660",
"userName": "fanffair",
"userFullName": "fanffair",
"userAction": "recommends",
"pageid": "usatoday",
"fanPageName": "USA TODAY",
"description": "A missing Indonesian man was found inside a massive python on the island of Sulawesi, according to local authorities and news reports. ",
"catid": "NewsAndMedia",
"type": "link",
"name": "Indonesian man swallowed whole by python",
"picture": "https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQBQf3loH5-XP6hH&w=130&h=130&url=https%3A%2F%2Fwww.gannett-cdn.com%2F-mm-%2F1bb682d12cfc4d1c1423ac6202f4a4e2205298e7%2Fc%3D0-5-1821-1034%26r%3Dx633%26c%3D1200x630%2Flocal%2F-%2Fmedia%2F2017%2F03%2F29%2FUSATODAY%2FUSATODAY%2F636263764866290525-Screen-Shot-2017-03-29-at-9.27.47-AM.jpg&cfs=1&_nc_hash=AQDssV84Gt83dH2A",
"full_picture": "https:\/\/external.xx.fbcdn.net\/safe_image.php?d=AQBQf3loH5-XP6hH&w=130&h=130&url=https%3A%2F%2Fwww.gannett-cdn.com%2F-mm-%2F1bb682d12cfc4d1c1423ac6202f4a4e2205298e7%2Fc%3D0-5-1821-1034%26r%3Dx633%26c%3D1200x630%2Flocal%2F-%2Fmedia%2F2017%2F03%2F29%2FUSATODAY%2FUSATODAY%2F636263764866290525-Screen-Shot-2017-03-29-at-9.27.47-AM.jpg&cfs=1&_nc_hash=AQDssV84Gt83dH2A",
"message": "Akbar Salubiro was reported missing after he failed to return from harvesting palm oil.",
"link": "http:\/\/www.usatoday.com\/story\/news\/nation-now\/2017\/03\/29\/missing-indonesian-man-swallowed-whole-reticulated-python\/99771300\/",
"source": "",
"likes": {
"summary": {
"total_count": "500"
}
},
"comments": {
"summary": {
"total_count": "61"
}
},
"shares": {
"count": "4"
}
}]
}
Code snippet:
String jPath = "/data[Array][1]/likes[Object]/summary[Object]/total_count[String]";
String value = JSONDataReader.getStringValue(jPath, jsonData);

Related

Parsing nested JSON in Java

I have a weird JSON which looks like this
[
[
{
"id": "1",
"clientId": "user"
},
{
"id": "2",
"clientId": "user"
}
],
[
{
"Status": "NotCompleted",
"StatusId": 0
},
{
"Status": "Importing",
"StatusId": 10
}
]
]
I am trying to parse it with Gson or JsonParser.
Classes look like this
public class Event {
public String id;
public String clientId;
}
public class Status {
public String Status;
public String StatusId;
}
public class AllEvents {
public Event[] events;
public Status[] statuses;
}
But when I am trying to parse it with Gson (e.g)
AllEvents[] r = new Gson().fromJson(response, AllEvents[].class);
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 6 path $[0]
Could you please help me out with parsing this kind of model? Cannot find what I am doing wrong in this case.
Thanks in advance
To solve such a problem there is two approaches:
First Approach:
Change your JSON file content(allEvents) to :
[
{
"events": [
{
"id": "1",
"clientId": "user"
},
{
"id": "2",
"clientId": "user"
}
],
"statuses": [
{
"Status": "NotCompleted",
"StatusId": 0
},
{
"Status": "Importing",
"StatusId": 10
}
]
}
]
and after that, your code will work perfectly.
Second Approach:
you need to code according to match above JSON structure:
Please find below the code which will help you.
Gson gson = new Gson();
Object[] r = gson.fromJson(loadDataAsString(), Object[].class);
AllEvents allEvents = new AllEvents();
//if your json structure position is fixed the do this commented code
//allEvents.events = gson.fromJson(gson.toJson(r[0]), Event[].class); //if your json Event structure position is fixed at 0 index
//allEvents.statuses = gson.fromJson(gson.toJson(r[1]), Status[].class); //if your json Status structure position is fixed at 1 index
//if your json structure position is not fixed the do below code
allEvents.events = Arrays.stream(r)
.flatMap(x -> Arrays.stream(gson.fromJson(gson.toJson(x), Event[].class)))
.filter(y -> y.id != null).toArray(Event[]::new);//id as primary key
allEvents.statuses = Arrays.stream(r)
.flatMap(x -> Arrays.stream(gson.fromJson(gson.toJson(x), Status[].class)))
.filter(y -> y.Status != null).toArray(Status[]::new);//Status as primary key
System.out.println(gson.toJson(allEvents));//{"events":[{"id":"1","clientId":"user"},{"id":"2","clientId":"user"}],"statuses":[{"Status":"NotCompleted","StatusId":"0.0"},{"Status":"Importing","StatusId":"10.0"}]}
Use JsonReader instead. So if you know you json starts with [ and ends with ] use read with beginArray. Your in is an InputStream, it can be a file, socket stream or string stream.
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
List<YourMessage> messages = new ArrayList<YourMessage>();
reader.beginArray();
while (reader.hasNext()) {
messages.add (do something with reader);//<-- that is pseudo code
}
reader.endArray();
return messages;
For more detail check this link https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.0/com/google/gson/stream/JsonReader.html
Solved issue in this way:
org.json.JSONArray allEvents = new org.json.JSONArray(response.getBodyAsString());
As a result I received JSONArray with 2 elements. Then extracted needed one through
allEvents.getJSONArray(0)
And then mapped in previous way with jackson ObjectMapper.
Thx for replies!

Parse JSON with JsonArray and HashMap

I need to parse the following JSON and add values from it into three different Java objects. I was thinking to form other 3 Jsons in order to do this. I have some issues with parsing, as the JSON is a little bit complicated. The JSON is below:
{
"totalCount": 1,
"results": [
{
"teleCommunications": [
{
"areaCode": "100",
"telephoneNumber": "300-2444",
"internationalAreaCode": "",
"communicationType": 1
},
{
"areaCode": "100",
"telephoneNumber": "200-2555",
"internationalAreaCode": "",
"communicationType": 5
}
],
"delegate": {
"id": 0,
"range": 0,
},
"name": "Andrew",
"composedKey": {
"id": 615,
"range": 50,
},
"isBranchAddress": false,
"emailAddresses": [
{
"emailAddressType": 9,
"emailAddress": "andrew.brown#gmail.com"
}
],
"name": "Brown",
"zipCodeCity": "65760 Leipzig",
"salutation": "Mr.",
"openingDate": "2019-09-20",
"streetHouseNumber": "Offenbach. 37",
"modificationTimestamp": "2018-01-27"
}
]
}
I need to get separately the values from name, zipCodeCity, salutation, openingDate, streetHouseNumber in a JSON ( or any other way) , emailAddresses in a different JSON and the other data in another one.
I tried with this piece of code:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
HashMap<String, Object> result = new ObjectMapper().readValue(response, HashMap.class);
Object object = result.get("results");
List<HashMap<String, String>> jsonValues = (List<HashMap<String, String>>)object;
for(String key : jsonValues.get(0).keySet()){
System.out.println("name value " + jsonValues.get(0).get("name"));
System.out.println("zip code City " + jsonValues.get(0).get("zipCodeCity"));
}
The problem is that I would not go for such a hardcoded way...it is not very suitable.
Does anyone know a better approach for storing the values I need and parsing the Json more optimally?
Thank you
Look for this link, there's a demo application specially for you: https://github.com/nalmelune/jackson-demo-58591850 (look at JacksonTest)
First of all, you'll need data-classes for this (or so called dto), representing structure. You can use online generators for that (google "json to java dto online") or do it yourself. For example, here's root object (see github link for more):
public class Root {
private int totalCount;
private List<Results> results;
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalCount() {
return this.totalCount;
}
public void setResults(List<Results> results) {
this.results = results;
}
public List<Results> getResults() {
return this.results;
}
}
Then configure your ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
And use it (don't create new mapper, as it is in your example):
Root result = mapper.readValue(response, Root.class);
Finally, you can access it as usual Plain Old Java Objects:
for (Results resultItem : result.getResults()) {
System.out.println(resultItem.getSalutation());
System.out.println(resultItem.getName());
System.out.println(resultItem.getZipCodeCity());
System.out.println(resultItem.getOpeningDate());
System.out.println(resultItem.getStreetHouseNumber());
}
To make it work be sure validate your json (there were invalid commas after "range", and "name" comes twice and so on, it fixed on github). And be sure to include jsr310 in classpath by adding com.fasterxml.jackson.datatype:jackson-datatype-jsr310 module. You will need it for LocalDate and LocalDateTime objects.
You may create java class something like below
#Data
class MyCustomClass{
int totalCount;
List<TeleCommunicationDetail> results;
// other props
}
Next you can add attributes to TeleCommunicationDetail and finally you can use MyCustomClass reaonseInJavaObject = objectMapper.readValue(myJson,MyCustomClass.class);
Refer to this question for details.
Your approach is correct, as you simply read your JSON object as Map<String, Object> which always will work (as long as JSON Object is valid). And then you retrieve your values that you expect to be there. Another approach is to create a Class that maps to your original JSON and parse JSON with ObjectMapper into your class. Then you can retrieve your data with your class setters and getters. In this case, you don't need to use key Strings like "results" etc but you have to ensure that your JSON is not only valid JSON but always conforms to your class. Pick your option...

Parse JSON file to java objects using Gson

I am having issues with "converting" the data in the JSON file to the required java objects. The JSON file looks something like this:
{
"initialInventory": [
{"bookTitle": "Harry Poter", "amount": 10, "price": 90},
{"bookTitle": "The Hunger Games", "amount": 90, "price": 102}
],
"initialResources":[
{"vehicles":[
{"license":123483, "speed": 2},
{"license":999994, "speed": 4}
]
}
],
"services":{
"time": {
"speed": 1000,
"duration": 24
},
"selling": 6,
"inventoryService": 3,
"logistics": 4,
"resourcesService": 2,
"customers": [
{
"id": 123456789,
"name": "Bruria",
"address": "NewYork 123",
"distance":33,
"creditCard":{"number":67890,"amount":88},
"orderSchedule": [
{"bookTitle": "Harry Poter", "tick": 3},
{"bookTitle": "The Hunger Games", "tick": 3}
]
},
{
"id": 234567891,
"name": "Shraga",
"address": "BeerSheva 3333",
"distance":12,
"creditCard":{"number":453536,"amount":220},
"orderSchedule": [
{"bookTitle": "The Hunger Games", "tick": 12}
]
}
]
}
All the JSON files I will be dealing with (for now) have the same structure.
I tried using Gson to parse the file (I am required to use Gson for this),
I've searched many videos and tutorials regarding the matter, but most of them were over-simplified or simply irrelevant, and it feels like either there are too many ways to do it, or that I just can't understand how to do it correctly.
This is what I tried so far:
public class BookStoreRunner {
public static void main(String[] args) throws IOException { //has to be added, we get an error without it. can be dealt with try-catch, doesn't matter.
Gson gson=new Gson();
File jsonfile= new File("pathtofile"); //should be the actual path to the file.
InputStream iStream= new FileInputStream(jsonfile);
Reader reader = new InputStreamReader(iStream);
JsonReader jsonReader =gson.newJsonReader(reader);
JsonParser parser= new JsonParser();
BookInventoryInfo[] books=gson.fromJson("initialInventory",BookInventoryInfo[].class);
ResourcesHolder.getInstance().load(gson.fromJson("vehicles",DeliveryVehicle[].class));
int timespeed= gson.fromJson("speed",int.class);
int timeduration=gson.fromJson("duration",int.class);
int numOfSellers=gson.fromJson("selling",int.class);
int numOfInventories=gson.fromJson("inventoryService",int.class);
int numOfLogistics=gson.fromJson("logistics",int.class);
int numOfResourceServices=gson.fromJson("resourcesService",int.class);
Customer[] customers=gson.fromJson("customers",Customer[].class);
/* JsonElement jElement = parser.parse(reader); // JsonElement is equivalent to a list in java
JsonObject jObject = jElement.getAsJsonObject(); //equivalent to an object of a class that implements the 'map' interface, e.g contains pairs of key:value
JsonObject initialInventory = jObject.getAsJsonObject("initialInventory");
JsonArray inventory =initialInventory.getAsJsonArray(); //it is an array (json syntax), but a JSONArray is not iterable.
// dealing with inventory
int i=0; //counter for all the books to be inserted to inventory array (index)
for (Map.Entry<String,JsonElement> entry: initialInventory.entrySet()) //.entrySet() gives a set view of the JSONObject, which is iterable
{
}
JsonArray iResources= jObject.getAsJsonArray("initialResources");
JsonObject veh = iResources.get(0).getAsJsonObject();
//initialization of java object, for the initialResources
JsonObject services=jObject.getAsJsonObject("services");
JsonObject timedata=jObject.getAsJsonObject("services").getAsJsonObject("time");
int numOfSelling= gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("selling"), int.class);
int numOfInventories= gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("inventoryService"), int.class);
int numOfIogistics=gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("logistics"),int.class);
int numOfResourceServices= gson.fromJson(jObject.getAsJsonObject("services").getAsJsonPrimitive("resourcesService"),int.class);
JsonArray jsonCustomers = jObject.getAsJsonObject("services").getAsJsonArray("customers");
JsonObject jsonCustomersObject=jObject.getAsJsonObject("services").getAsJsonObject("customers");
Customer[] customers = new Customer[5000]; // check if there's a problem with this part. unsure how many customers there are, or if we need\can use a list.
int i=0; //customers index
for (Map.Entry<String,JsonElement> entry: jsonCustomersObject.entrySet())
{ //assuming we will implement a constructor for Customer which receives all the required values
}
*/
I've tried parsing the file with a different approach, it's marked as a comment at the end of the code.
I can't figure out if the problem is with my understanding of JSON in general, my knowledge of java I\O usage or that I'm simply missing something.
How can I create the Objects I need from the JSON file effectively with Gson?

Trouble parsing a json array inside a json array

I am having trouble parsing a simple json in java. Here is the sample json.
[
{
"politics": [
{
"type": "admin2",
"friendly_type": "country",
"name": "United States",
"code": "usa"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Gratiot",
"code": "26_057"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Eighth district, MI",
"code": "26_08"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Clinton",
"code": "26_037"
},
{
"type": "admin4",
"friendly_type": "state",
"name": "Michigan",
"code": "us26"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Fourth district, MI",
"code": "26_04"
}
],
"location": {
"latitude": 43.111976,
"longitude": -84.71275
}
}
]
Now this gives me the correct json index.
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
String jsonobj = array.get(0).toString();
{"politics":[{"code":"usa","name":"United States","type":"admin2","friendly_type":"country"},{"code":"26_057","name":"Gratiot","type":"admin6","friendly_type":"county"},{"code":"26_08","name":"Eighth district, MI","type":"constituency","friendly_type":"constituency"},{"code":"26_037","name":"Clinton","type":"admin6","friendly_type":"county"},{"code":"us26","name":"Michigan","type":"admin4","friendly_type":"state"},{"code":"26_04","name":"Fourth district, MI","type":"constituency","friendly_type":"constituency"}],"location":{"latitude":43.111976,"longitude":-84.71275}}
But I cant seem to get the attribute that I want from it.
JSONObject obj1 = new JSONObject(jsonobj);
String n = obj1.getString("admin4");
System.out.println(n);
All that I need from this json is the state which is Michigan. Where am I wrong?
Help would be really appreciated.
First, array.get(0) will get you the first element from the main array. This first element is a JSON object that has two properties politics and location. You seem to be interested in a value that is inside the array value of the politics property. You'll have to use this ((JSONArray)((JSONObject)array.get(0)).get("politics")) to get that array.
Second, admin4 is not a property it is actually a value of the type property. You'll have to loop through the array to find it.
Here is a complete example:
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
JSONArray politics = ((JSONObject)array.get(0)).get("politics"));
JSONObject obj = null;
for(int i = 0; i < politics.size(); i++){
if(((JSONObject)politics.get(i)).getString("type").equals("admin4")){
obj = ((JSONObject)politics.get(i));
}
}
if(obj != null){
// Do something with the object.
}
It seems that you're using the simple json library. I don't remember exactly if it is .get("politics") or .getJSONObject("politics"). There may be other mistakes in method names in my example.
the best solution to simplify your search and other operations on json object, is the convert json string to java object and doing your operations.
for convert json string to java object use follow code:
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
YourObject myObject;
ObjectMapper mapper = new ObjectMapper();
try{
myObject= mapper.readValue(jsonData, myObject.class);
}
catch (Exception e) {
e.printStackTrace();
}
for example define your class ass follow :
public class myObject{
private List<Politics> politics;
private Location location;
// define getters and setters
}
define Politics and Location class:
public class Politics
{
String type;
String friendly_type;
String name;
String code;
// define getters and setters
}
public class Location
{
String latitude;
String longitude;
// define getters and setters
}
It's because your are trying to get the inner element of the JSON Object.
try
JSONObject obj1 = new JSONObject(jsonobj);
JSONArray arr = (JSONArray) obj1.getObject("politics");
You will get a JSONArray object which further constitutes of JSON objects.
Now in order to get values using the key you must iterate array as given below:
for(int i=0; i<arr.size(); i++){
JSONObject obj = arr.getJSONArray(i);
System.out.println(obj.getString("type"));
}
which will now provide you with output:
admin2
admin6
constituency
admin6
admin4
constituency

JSON different objects in an array

At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")

Categories

Resources