Chage your code like,
JSONArray c = jsonObject.getJSONArray("Channel_12"); //Change your code from here
JSONArray array = c.getJSONArray(0);
String data = c.getString(1);
Log.i("#Values", array.getString(0) + "\t" + data);
See my result,

Chage your code like,
JSONArray c = jsonObject.getJSONArray("Channel_12"); //Change your code from here
JSONArray array = c.getJSONArray(0);
String data = c.getString(1);
Log.i("#Values", array.getString(0) + "\t" + data);
See my result,

It looks like your JSONArray contains a JSONArray and a JSONObject. A JSONArray is not a JSONObject.
Are you in control of the source format? Because it looks a little weird.
The structure is as so: At position 0 is an array with one object, and a position 1 is an object.
Your code can be changed to this:
org.codehaus.jettison.json.JSONArray c = obj.getJSONArray("Channel_12");
JSONArray array = c.getJSONArray(0);
JSONObject obj2 = array.getJSONObject(0);
System.out.println(obj2.getString("to").toString());
System.out.println(obj2.getString("msg").toString());
Parse nested object Json file in JAVA
java - Building a Nested JSON within looping - Stack Overflow
java - read nested json object using loop - Stack Overflow
Looping through nested json object
Videos
you need a recursive function.
function iterateTree(object) {
if (!object) { //recursion stop criteria || you need to implement what your stop criteria is
return;
}
//doSomthingWithObject();
iterateTree(object.children);
}
I'm sure you figure it out how to use it in java.
You may try
public void printJsonObject(JSONObject jsonObj) {
for (String keyStr : jsonObj.keySet()) {
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
}
Create a new JSONObject each time, inside the loop.
JSONArray outer = new JSONArray();
JSONObject js = null;
List<String> str = new ArrayList<String>();
str.add("London");
str.add("Tokyo");
str.add("Washington");
int res = 3;
for(int i=0;i<res;i++){
js= new JSONObject();
js.put("Value", i);
js.put("Name", "John");
js.put("Cities", str);
outer.add(js);
}
System.out.println(outer);
Also, you'll probably get the same issue if changing cities anytime, so unless they will always remain the required three, create a new list for every object.
You need to create new JSON object for each Value,Name, Cities pair. So you need to put it inside second for loop. Like this
for(int i=0;i<res;i++){
js= new JSONObject();
You can do it using ecmascript 5's forEach method:
land.forEach(function(entry){
console.log(entry.name + " : " + entry.value)
} );
or use jquery to support legacy web browsers:
$.each(land,function(index,entry) {
console.log(entry.name + " : " + entry.value)
});
Don't loop through the subobject, just show its properties.
var land = [{
"name": "city",
"value": "Los Angeles"
}, {
"name": "state",
"value": "California"
}, {
"name": "zip",
"value": "45434"
}, {
"name": "country",
"value": "USA"
}];
$.each(land, function(index, object) {
console.log(object.name, ": ", object.value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Hello, not quite sure if this is the best place to ask. Sorry if it isn't.
So the question: I am trying to put all values in an array from some GeoJSON that I have for a popup marker on a map. I am also using React so this may have caused some issues. From what I've been able to gather is the best way to do this is recursively this is my idea of how to accomplish this.
onEachFeature = (feature, layer) => {
const placesTabContent = [];
for (const prop in feature.properties.place) {
if (typeof(feature.properties.place[prop]) === 'object') {
//Recursive call here?? Not sure how to accomplish.
} else {
placesTabContent.push('<b>' + prop + '</b> : ' + feature.properties.place[prop] + '<br>')
}
}
const content = '<div class="tabs">' +
'<div class="tab" id="places_tab">' +
'<div class="content">'
+ placesTabContent +
'</div>' +
'</div>' +
'<div class="tab" id="location_tab">' +
'<div class="content">' +
+ //Will be location info when nested GeoJSON works +
'</div>' +
'</div>' +
'<ul class="tabs-link">' +
'<li class="tab-link"> <a href="#places_tab"><span>Places</span></a></li>' +
'<li class="tab-link"> <a href="#location_tab"><span>Location</span></a></li>' +
'</ul>' +
'</div>'
layer.bindPopup(content)
}onEachFeature gets passed into a GeoJSON component. If this makes no sense let me know. Using Leaflet.js / React-Leaflet.
I Assume you have List messages :
Here is how you can browse through all children with both recursion and iterative way :
List<Message> messages = //you already have that
System.out.println("Using Recusion : ");
for (Message message : messages) {
printMessage(message);
}
System.out.println("Using Iterative : ");
Stack<Message> stack = new Stack<>();
stack.addAll(messages);
while (!stack.empty()) {
Message item = stack.pop();
System.out.println(item.getId() + ":" + item.getUser_id() + ":" + item.getMessage());
for (Message chidren : item.getChildren()) {
stack.push(chidren);
}
}
and here is the printMessage method :
public static void printMessage(Message pmessage) {
System.out.println(pmessage.getId() + ":" + pmessage.getUser_id() + ":" + pmessage.getMessage());
for (Message message : pmessage.getChildren()) {
printMessage(message);
}
}
public void printJsonObject(JSONObject jsonObj) {
for (String keyStr : jsonObj.keySet()) {
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
//for nested objects iteration if required
if (keyvalue instanceof JSONObject)
printJsonObject((JSONObject)keyvalue);
}
}
Maybe this will help:
JSONObject jsonObject = new JSONObject(contents.trim());
Iterator<String> keys = jsonObject.keys();
while(keys.hasNext()) {
String key = keys.next();
if (jsonObject.get(key) instanceof JSONObject) {
// do something with jsonObject here
}
}
for my case i found iterating the names() works well
for(int i = 0; i<jobject.names().length(); i++){
Log.v(TAG, "key = " + jobject.names().getString(i) + " value = " + jobject.get(jobject.names().getString(i)));
}
The problem in the above code is JSONObject obj = new JSONObject(); initialised only one but you need to create inside the loop. This code gives the expected output as you want:
public static void main(String[] args) throws JSONException {
JSONObject index = new JSONObject();
JSONObject jsonRecipe = new JSONObject();
JSONObject metadataReq = new JSONObject();
metadataReq.put("technology","Ceramics");
metadataReq.put("material","Nylon");
metadataReq.put("color","Green");
JSONArray keys = metadataReq.names();
for (int i = 0; i < metadataReq.length (); i++) {
String key = keys.getString (i);
String val = metadataReq.getString (key);
String j = Integer.toString(i);
JSONObject obj = new JSONObject();
obj.put("attribute", key);
obj.put("value", val);
obj.put("mandatory", "rule");
index.put(j, obj);
jsonRecipe.put("metadata", index);
}
System.out.println(jsonRecipe);
}
You only created 1 object and inserted it 3 times, as opposed to creating 3 distinct objects.
Maybe you're not using the latest version of a JSON for Java Library.
json-simple has not been updated for a long time, while JSON-Java was updated 2 month ago.
JSON-Java can be found on GitHub, here is the link to its repo: https://github.com/douglascrockford/JSON-java
After switching the library, you can refer to my sample code down below:
public static void main(String[] args) {
String JSON = "{\"LanguageLevels\":{\"1\":\"Pocz\\u0105tkuj\\u0105cy\",\"2\":\"\\u015arednioZaawansowany\",\"3\":\"Zaawansowany\",\"4\":\"Ekspert\"}}\n";
JSONObject jsonObject = new JSONObject(JSON);
JSONObject getSth = jsonObject.getJSONObject("LanguageLevels");
Object level = getSth.get("2");
System.out.println(level);
}
And as JSON-Java open-sourced, you can read the code and its document, they will guide you through.
Hope that it helps.
You will have to iterate step by step into nested JSON.
for e.g a JSON received from Google geocoding api
{
"results" : [
{
"address_components" : [
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Bhopal",
"short_name" : "Bhopal",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Madhya Pradesh",
"short_name" : "MP",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Bhopal, Madhya Pradesh, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
},
"location" : {
"lat" : 23.2599333,
"lng" : 77.412615
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 23.3326697,
"lng" : 77.5748062
},
"southwest" : {
"lat" : 23.0661497,
"lng" : 77.2369767
}
}
},
"place_id" : "ChIJvY_Wj49CfDkR-NRy1RZXFQI",
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
I shall iterate in below given fashion to "location" : { "lat" : 23.2599333, "lng" : 77.412615
//recieve JSON in json object
JSONObject json = new JSONObject(output.toString());
JSONArray result = json.getJSONArray("results");
JSONObject result1 = result.getJSONObject(0);
JSONObject geometry = result1.getJSONObject("geometry");
JSONObject locat = geometry.getJSONObject("location");
//"iterate onto level of location";
double lat = locat.getDouble("lat");
double lng = locat.getDouble("lng");