for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).
Hope this helps.
Answer from Buhake Sindi on Stack OverflowNew to Java, wanted some help with reading .json object arrays.
How to turn json objects into an array of json objects using Java?
json - How to create correct JSONArray in Java using JSONObject - Stack Overflow
json - Accessing members of items in a JSONArray with Java - Stack Overflow
Videos
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).
Hope this helps.
You can prefer quick-json parser to meet your requirement...
quick-json parser is very straight forward, flexible, very fast and customizable. Try this out
[quick-json parser] (https://code.google.com/p/quick-json/) - quick-json features -
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Heirarchy
Easy to use # Very Less foot print
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-json validating parser
Require JDK 1.5 # No dependency on external libraries
Support for Json Generation through object serialization
Support for collection type selection during parsing process
For e.g.
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).
Hope this helps.
Answer from Buhake Sindi on Stack Overflow// Create a JSON object from the response
JSONObject jsonResponse = new JSONObject(response.toString());
// Write the JSON object to a file
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.json"))) {
writer.write(jsonResponse.toString(4)); // The number specifies the indentation for pretty printing
}
System.out.println("JSON response written to output.json");
} else {
System.out.println("HTTP request failed with response code: " + responseCode);
}
// Read the JSON data from the file
String jsonContent = new String(Files.readAllBytes(Paths.get("output.json")));
// Create a JSONObject from the JSON data
JSONObject jsonObject = new JSONObject(jsonContent);
JSONArray result = jsonObject.getJSONArray("result");
JSONObject skey = result.getJSONObject(5);
String memo = skey.getString("memo");
System.out.println("Value of 'key' in the JSON object: " + memo);
// Close the connection
connection.disconnect();Code ^^
i am trying to read a specific sub-key of a .json array which is saved from an http GET request.
the structure of the .json file is something like this:
"jsonarray": [{
"subkey1": "a"
"subkey2": "b"
"subkey3": "c"
"subkey4": "d"
"subkey5": "e"
"subkey6": "f"
"subkey7": "g"
}],
"key1": "h",
"key2": "i"i want to read the value of subkey5 i.e. "e", but when i try to do it, it gives me an error. where am i going wrong?
Hi. I'm new to java and stuck wondering how I would go about turning something like this: {} {} {} into this: [{},{},{}]. I'm trying to figure out how to do this to my incoming json data using Java. The data has like 20 similar objects, with the same keys but with constantly changing values.
Any help is much appreciated.
Sincerely,
your friendly neighborhood noob
Here is some code using java 6 to get you started:
JSONObject jo = new JSONObject();
jo.put("firstName", "John");
jo.put("lastName", "Doe");
JSONArray ja = new JSONArray();
ja.put(jo);
JSONObject mainObj = new JSONObject();
mainObj.put("employees", ja);
Edit: Since there has been a lot of confusion about put vs add here I will attempt to explain the difference. In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.
An example of this using the builder pattern in java 7 looks something like this:
JsonObject jo = Json.createObjectBuilder()
.add("employees", Json.createArrayBuilder()
.add(Json.createObjectBuilder()
.add("firstName", "John")
.add("lastName", "Doe")))
.build();
I suppose you're getting this JSON from a server or a file, and you want to create a JSONArray object out of it.
String strJSON = ""; // your string goes here
JSONArray jArray = (JSONArray) new JSONTokener(strJSON).nextValue();
// once you get the array, you may check items like
JSONOBject jObject = jArray.getJSONObject(0);
Hope this helps :)
Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:
for (int i = 0; i < recs.length(); ++i) {
JSONObject rec = recs.getJSONObject(i);
int id = rec.getInt("id");
String loc = rec.getString("loc");
// ...
}
An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:
JSONArray lineItems = jsonObject.getJSONArray("lineItems");
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String key = jsonLineItem.getString("key");
String value = jsonLineItem.getString("value");
...
}
Works great... :)