I've been having some problems iterating through a JSON object in Java.
Specifically, I'd like to save each value for "name" to the string array "nameList". I've looked up how to do this, and I haven't found a way for this situation.
String[] nameList = new String[]{};
{
"data": {
"Narray": {
"0":
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
"1":
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
}
}
Ideally you'd want Narray to be an actual JSON array, enclosed in [], with each element being another object, containing the property you need, like this:
{
"Narray": [
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
]
}
Then you can use jackson to decode the JSON string into a POJO structure. Once you have the objects, you can iterate over the array and retrieve the property you need into a list.
I assume that you only want to save each value of name into a String[] (string array), so you don't need to deserialize the JSON string to POJO, just use basic API to achieve what you want as follows:
BTW, your JSON string is invalid, you miss a right bracket.
ObjectMapper mapper = new ObjectMapper();
JsonNode nArray = mapper.readTree(jsonStr).get("data").get("Narray");
String[] nameList = new String[nArray.size()];
for (int i = 0; i < nArray.size(); i++) {
nameList[i] = nArray.get(String.valueOf(i)).get("name").asText();
}
System.out.println(Arrays.toString(nameList));
Console output:
[studio, venue]
I have a json arrary with many json messsages. I then parse the json message to process each json object.
I need to figure out how to take a single json object that fails and append all the failed json objects back
into another json array to create a new file. I'm not sure how to convert a json object from the parseText() method
back to a normal json message or how to append objects back into a json array to create a file. Can someone help me with this?
Main json file array
[
{
"Account": "1",
"Name": "Test1"
},
{
"Account": "2",
"Name": "Test2"
},
{
"Account": "3",
"Name": "Test3"
},
{
"Account": "4",
"Name": "Test4"
}
]
String sJson = groovy.json.StringEscapeUtils.unescapeJava(jsonFile.toString());
jsonResp = new groovy.json.JsonSlurper().parseText(sJson));
for( int x=0; x < jsonResp?.size(); x++ ) {
processJson( jsonResp[x] )
}
void processJson( Object jsonResp ) {
If object message fails in this function, need to convert the json object back into a json message
and append it to a jsonArray to create a new json file.
}
This is what the new json file would like if test samples 2 & 4 failed
[
{
"Account": "2",
"Name": "Test2"
},
{
"Account": "4",
"Name": "Test4"
}
]
I found the answer to my question.
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonResp);
println jsonArray.toString()
I want create a pojo from a json like this
{
"1": [
{
"idmapel": 1,
"label": "Fisika"
},
{
"idmapel": 2,
"label": "Kimia"
},
{
"idmapel": 3,
"label": "Biologi"
},
{
"idmapel": 4,
"label": "Matematika"
},
],
"2":[
{
"idmapel": 1,
"label": "Fisika"
}
]
}
when i generate from http://www.jsonschema2pojo.org/ it created a 1 and 2 class, but imagine if i have more than 2 keys. i want to be able to access element by something like this ObjectClass::getList(1) or ObjectClass::getList(2)
You can use a Map to do this.
Map<String, List<Pojo>> map = deserialize(jsonSring);
where Pojo is the class which has fields idmapel and label, deserialize is a method which deserializes the json to object and jsonString is the json string value to deserialize. Then you can access lists with keys
List<Pojo> list1 = map.get("1");
List<Pojo> list2 = map.get("2");
I have a JSON source with more empty_slots elements (in the example exist below only one, but in the reality exist more stations with empty_slots). How can I sum the values from empty_slots and return as double? Thanks!
JAVA
public static double getValueFromJSONString(String jString) throws JSONException
{
JSONObject json = new JSONObject(jString);
return json.getJSONObject("empty_bikes").getDouble(jString);
}
JSON
{"network": {
"company": [
"Gewista Werbegesellschaft m.b.H"
],
"id": "citybike-wien",
"location": {
"city": "Wien",
},
"stations": [
{
"empty_slots": 3,
"extra": {
"slots": "26",
},
"free_bikes": 23
}]}
Checkout JsonPath. Below code is not tested but should work with RestAssured dependency - https://github.com/rest-assured/rest-assured
JsonPath jsonPath = new JsonPath(jsonString);
List<Integer> companyEntityIds = jsonPath.getList("network.stations.empty_slots");
Once you have the array you can just use a stream or whatever to add these up.
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")