I need to read a JSON file with following form:
{
"Data":[{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33",
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
My question stands : How do I access individual elements given it's sometimes JSONObject and sometimes JSONArray. I tried using org.json library but I'm failing to access anything after this line -> "array":[. I tried various combinations of JSONObject and JSONArray up to no avail.
My latest code looked something like this:
List<Data> data= new ArrayList<>();
String rawJson = getJsonAsString();
JSONObject outer = new JSONObject(rawJson);
JSONArray jArr= outer.getJSONArray("Data");
JSONObject inner= outer.getJSONObject("array");
for(int i =0; i<jArr.length(); i++){
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo"); <-- this works,
String 1foo = jsonEvent.getString("1foo"); <-- but this doesn't and i cant access it
I tried dozens of different solutions(tried myself and tried to find something here as well, but every case with those nested arrays is different and I can't add those solutions together to get answer for my case)
You can increase your readability if you beautify your raw JSON string:
{
"Data":[
{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33"
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{ and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
...
],
...
}
]
}
So, stick to the following code:
JSONArray jArr = outer.getJSONArray("Data");
jArr is now filled with array of your Object.
And to loop through your Object array, you can use a for-loop which you have done it correctly.
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
}
And now each jsonEvent contains your Object, which you can access the Object by their type.
For example, if you would like to access foo, you can use:
String foo = jsonEvent.getString("foo"); // foo = "22"
String bar = jsonEvent.getString("bar"); // bar = "33"
// Note that your array is another Array, you need to get it as JSONArray first
JSONArray arrayJson = jsonEvent.getJSONArray("array");
And as 1foo is in the first Object for your array, you need to access it like this:
JSONObject firstObjectInArray = arrayJson.getJSONObject(0);
String target = firstObjectInArray.getString("1foo"); // target = "22"
And to access foofoo, as it is an attribute of the JSON Object anotherData, so you should obtain anotherData as JSONObject first, and then you can access foofoo:
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo"); // foofoo = "22"
So the full code within your for-loop should look like this:
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo");
JSONArray arrayJson = jsonEvent.getJSONArray("array");
String target = arrayJson.getJSONObject(0).getString("1foo");
// Add to get foofoo
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo");
}
I have a JSONArray which contains multiple JSONObjects
[
{
"record":[
{
"timeStamp":"2018-10-11T05:36:51+00:00",
"code":200,
"text":"OK"
},
{
"hostname":"qwe",
"address":"192.168.1.1",
"type":"A",
"priority":"0",
"ttl":"3600"
},
{
"hostname":"www",
"address":"test.com",
"type":"CNAME",
"priority":"0",
"ttl":"3600"
}
]
},
{
"record":[
{
"timeStamp":"2018-10-11T05:36:52+00:00",
"code":200,
"text":"OK"
},
{
"hostname":"rty",
"address":"192.168.1.2",
"type":"A",
"priority":"0",
"ttl":"300"
},
{
"hostname":"*",
"address":"test",
"type":"CNAME",
"priority":"0",
"ttl":"3600"
}
]
}
]
How can I parse this JSONArray and export it as a CSV File.
This is what I have tried so far
File file=new File("/home/administrator/Desktop/test.csv");
String csv = jsonArray;
FileUtils.writeStringToFile(file, csv);
System.out.println("CSV created.");
My desired output is
timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl
2018-10-11T05:36:51+00:00,200,OK,qwe,192.168.1.1,A,0,300,www,test.com,CNAME,0,3600
2018-10-11T05:36:52+00:00,200,OK,rty,192.168.1.2,A,0,300,*,test,CNAME,0,3600
Is it possible to have an output like this given the JSONArray above?
Sorry for the late respond was bashing my keyboard for the past 30 minutes but I finally got it done, here is the code.
public static String getCSVData() throws IOException, JSONException {
Path jsonFile = Paths.get("json");
String json = new String(Files.readAllBytes(jsonFile), StandardCharsets.UTF_8);
JSONArray jsonArray = new JSONArray(json.trim());
List<List<String>> jsonArrays = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
List<String> jsonObjects = new ArrayList<>();
JSONArray record = jsonArray.getJSONObject(i).getJSONArray("record");
for (int i2 = 0; i2 < record.length(); i2++) {
JSONObject jsonObject = record.getJSONObject(i2);
if (i2 == 0) {
jsonObjects.add(jsonObject.get("timeStamp").toString());
jsonObjects.add(jsonObject.get("code").toString());
jsonObjects.add(jsonObject.get("text").toString());
} else {
jsonObjects.add(jsonObject.get("hostname").toString());
jsonObjects.add(jsonObject.get("address").toString());
jsonObjects.add(jsonObject.get("type").toString());
jsonObjects.add(jsonObject.get("priority").toString());
jsonObjects.add(jsonObject.get("ttl").toString());
}
}
jsonArrays.add(jsonObjects);
}
StringBuilder stringBuilder = new StringBuilder("timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl\n");
for(List<String> arrays : jsonArrays){
stringBuilder.append(StringUtils.join(arrays, ",")).append("\n");
}
return stringBuilder.toString().trim();
}
To explain the code first I looped over the first Array and then get the jsonObject of the first JSONArray and then get the jsonArray named "record" from the JsonObject I have gotten by looping over the first JSONArray and then loop over record and get all the items and save them into an ArrayList. and join them via StringUtils which is provided by JDK.
if you want to write it to file use this
Files.write(Paths.get("YOUR CSV FILE"), getCSVData().getBytes(StandardCharsets.UTF_8));
all the code I used are provided by JDK and org.json.
after we print out getCSVDate(); the output is:
timeStamp,code,text,hostname,address,type,priority,ttl,hostname,address,type,priority,ttl
2018-10-11T05:36:51+00:00,200,OK,qwe,192.168.1.1,A,0,3600,www,test.com,CNAME,0,3600
2018-10-11T05:36:52+00:00,200,OK,rty,192.168.1.2,A,0,300,*,test,CNAME,0,3600
I have this JSON structure:
{"metrics":[{
"type": "sum",
"column": ["rsales", "nsales"]
},
{
"type":"count",
"column":["ptype", "plan"]
}]
}
I am trying to read that JSON from Java and want to the output to be like:
str_sum="Sum"
str_sum_array[]= {"rsales" ,"nsales"}
str_count="count"
str_count_array[]= {"ptype" ,"plan"}
Here is my code so far:
JSONArray jsonArray_Metric = (JSONArray) queryType.get("metrics");
for (int i = 0; i < jsonArray_Metric.length(); i++) {
JSONObject json_Metric = jsonArray_Metric.getJSONObject(i);
Iterator<String> keys_Metrict = json_Metric.keys();
while (keys_Metrict.hasNext()) {
String key_Metric = keys_Metrict.next();
// plz help
}
}
How can I complete the code to produce the desired output?
Instead of using iterator you can use simple for-loop as below ..
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(queryType);
JSONArray jsonArray_Metric = (JSONArray) object.get("metrics");
for (int index = 0; index < jsonArray_Metric.size(); index++) {
JSONObject item = (JSONObject) jsonArray_Metric.get(index);
String type = (String) item.get("type");
JSONArray column = (JSONArray) item.get("column");
System.out.println("str_sum store=\"" + type + "\"");
System.out.println("str_count_array[] store=" + column);
}
Sample Run
str_sum store="sum"
str_count_array[] store=["rsales","nsales"]
str_sum store="count"
str_count_array[] store=["ptype","plan"]
If you want JSONArray to be displayed with curly braces instead of default (actual) braces i.e. square braces then you could so something like this while printing or you can even delete them by replacing them with empty string "".
System.out.println("str_count_array[] store " + column.toString().replace("[", "{").replace("]", "}"));
You can format your display code as you like by playing around with println statement.
I have a web system that returns a json string with the data that I need in an Android App. The string is below:
[
{"id":1,
"title":"Remove ViRuSeS",
"tagline":"Remove ViRuSeS",
"body":"Body",
"image":"index.jpg",
"steps":[
{"id":2,
"title":"Step 1",
"body":"Download Things!",
"position":1}
]
}
]
It should return an array of objects, with one of the object's items also being an array of items.
I am familiar with gson and have gotten this working in the past, but I always had to simplify my data down to just an object, which makes me end up have to make multiple calls to get the data.
Is there a good way to do this without having to map all of the possible values back into classes?
My last attempt was to just try to get something simple out of this and am getting a NullPointerException on the second of these lines:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("Steps");
change it to "steps" and not "Steps" , It will fix it:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("steps");
The full parsing method:
JSONArray mainArray = new JSONArray(json);
for (int i = 0 ; i < mainArray.length() ; i ++)
{
JSONObject currentItem = array.getJSONObject(i);
String title = currentItem.getString("title");
String body = currentItem.getString("body ");
....
JSONArray currentItemStepsArray = currentItem.getJSONArray("steps");
for (int j = 0 ; j < currentItemStepsArray.length() ; j ++)
{
....
}
}
Here, try this:
JSONArray topLevelArr = new JSONArray(json);
JSONArray stepArr = topLevelArr.getJSONObject(0).getJSONArray("steps");
I am using the package org.json package: I need help with getting the corect data from the json in java. this is the string I have in json:
{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]}
This is a listing and this is just a test, it will contain more than 2 items, so my questions is, I want to get the name of all locations, I want to populate a spinner with names in my android app.
How can I get the "Name":"Malmo" and so on....
???
The answer is simple....The JSON element starts with a { which is a JSON Object, and GetLocationsResults is a JSON Array of JSON Objects. In essence, I translated the JSON String to the following code...
JSONObject rootJson = new JSONObject(jsonString);
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
//Let's assume we need names....
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
//Test
for (String name: names) {
System.out.println(name);
}