How to split comma and semicolon separated string into a JSON object - java

I am not able to format below string :
"Sony,20,30,40;LG,1,4,8"
In below JSON format:
"reported": {
"SETS": [
{
"prodName": "Sony",
"fmtd": "20",
"lmtd": "30",
"lm": "40"
},
{
"prodName": "LG",
"mtd": "1",
"lmtd": "4",
"lm": "8"
}
]
}
I tried below code but not getting proper results.
String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 = stringFromProc.split("[\\;]");
JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split("[\\,]");
for(int j=0;j<array2.length;j++){
System.out.println(array2[j]);
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
jsonArrayRET.add(jsonSubObject);
jsonFinal.put("reported", jsonArrayRET);
}
}
But getting this format:
{"SETS":[{"lm":"40","lmtd":"30","mtd":"20","prodName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},]}
I know that I am making loop after splitting the comma separated array but not able to get the correct approach of how to split. Someone please suggest.

Just remove the internal loop
String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 = stringFromProc.split(";"); // simply use ;
// array1[0] = SONY,20,30,40
// array1[1] = LG,1,4,8
JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split(","); // simply use ,
// create jsonobjects
// when i=0 mean for sony and next time i = 1 mean for LG
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
// put every object in array
jsonArrayRET.add(jsonSubObject);
}
// finally put array in reported jsonobject
jsonFinal.put("reported", jsonArrayRET);
Note : ; and , are not special regular expressions characters so no escaping \\ is required and instead of long info just read about character class []

Move
jsonFinal.put("reported", jsonArrayRET);
outside of 2nd loop, you are overwritting reported object.
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split("[\\,]");
for(int j=0;j<array2.length;j++){
System.out.println(array2[j]);
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
jsonArrayRET.add(jsonSubObject);
}
jsonFinal.put("reported", jsonArrayRET);
}

Related

Nested JSONArray

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");
}

How to export a nested JSONArray to CSV?

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

Reading JSON from Java

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.

Mapping JSON to arrays/objects in Java - Android

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");

Getting JSONObject from JSONArray [duplicate]

This question already has answers here:
Accessing members of items in a JSONArray with Java
(6 answers)
Closed 6 years ago.
I am in a bit of a fix regarding the JSONObject that I am getting as a response from the server.
jsonObj = new JSONObject(resultString);
JSONObject sync_reponse = jsonObj.getJSONObject("syncresponse");
String synckey_string = sync_reponse.getString("synckey");
JSONArray createdtrs_array = sync_reponse.getJSONArray("createdtrs");
JSONArray modtrs_array = sync_reponse.getJSONArray("modtrs");
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
String deleted_string = deletedtrs_array.toString();
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
as you can see in the response that I am getting I am parsing the JSONObject and creating syncresponse, synckey as a JSON object createdtrs, modtrs, deletedtrs as a JSONArray. I want to access the JSONObject from deletedtrs, so that I can split them apart and use the values. i.e I want to extract companyid, username, date etc.
How can I go about this ?
Thanks for your input.
JSONArray objects have a function getJSONObject(int index), you can loop through all of the JSONObjects by writing a simple for-loop:
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
// do some stuff....
}
Here is your json:
{
"syncresponse": {
"synckey": "2011-09-30 14:52:00",
"createdtrs": [
],
"modtrs": [
],
"deletedtrs": [
{
"companyid": "UTB17",
"username": "DA",
"date": "2011-09-26",
"reportid": "31341"
}
]
}
}
and it's parsing:
JSONObject object = new JSONObject(result);
String syncresponse = object.getString("syncresponse");
JSONObject object2 = new JSONObject(syncresponse);
String synckey = object2.getString("synckey");
JSONArray jArray1 = object2.getJSONArray("createdtrs");
JSONArray jArray2 = object2.getJSONArray("modtrs");
JSONArray jArray3 = object2.getJSONArray("deletedtrs");
for(int i = 0; i < jArray3 .length(); i++)
{
JSONObject object3 = jArray3.getJSONObject(i);
String comp_id = object3.getString("companyid");
String username = object3.getString("username");
String date = object3.getString("date");
String report_id = object3.getString("reportid");
}
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
for(int i = 0; deletedtrs_array.length(); i++){
JSONObject myObj = deletedtrs_array.getJSONObject(i);
}
{"syncresponse":{"synckey":"2011-09-30 14:52:00","createdtrs":[],"modtrs":[],"deletedtrs":[{"companyid":"UTB17","username":"DA","date":"2011-09-26","reportid":"31341"}]
The get companyid, username, date;
jsonObj.syncresponse.deletedtrs[0].companyid
jsonObj.syncresponse.deletedtrs[0].username
jsonObj.syncresponse.deletedtrs[0].date
start from
JSONArray deletedtrs_array = sync_reponse.getJSONArray("deletedtrs");
you can iterate through JSONArray and use values directly or create Objects of your own type
which will handle data fields inside of each deletedtrs_array member
Iterating
for(int i = 0; i < deletedtrs_array.length(); i++){
JSONObject obj = deletedtrs_array.getJSONObject(i);
Log.d("Item no."+i, obj.toString());
// create object of type DeletedTrsWrapper like this
DeletedTrsWrapper dtw = new DeletedTrsWrapper(obj);
// String company_id = obj.getString("companyid");
// String username = obj.getString("username");
// String date = obj.getString("date");
// int report_id = obj.getInt("reportid");
}
Own object type
class DeletedTrsWrapper {
public String company_id;
public String username;
public String date;
public int report_id;
public DeletedTrsWrapper(JSONObject obj){
company_id = obj.getString("companyid");
username = obj.getString("username");
date = obj.getString("date");
report_id = obj.getInt("reportid");
}
}
When using google gson library.
var getRowData =
[{
"dayOfWeek": "Sun",
"date": "11-Mar-2012",
"los": "1",
"specialEvent": "",
"lrv": "0"
},
{
"dayOfWeek": "Mon",
"date": "",
"los": "2",
"specialEvent": "",
"lrv": "0.16"
}];
JsonElement root = new JsonParser().parse(request.getParameter("getRowData"));
JsonArray jsonArray = root.getAsJsonArray();
JsonObject jsonObject1 = jsonArray.get(0).getAsJsonObject();
String dayOfWeek = jsonObject1.get("dayOfWeek").toString();
// when using jackson library
JsonFactory f = new JsonFactory();
ObjectMapper mapper = new ObjectMapper();
JsonParser jp = f.createJsonParser(getRowData);
// advance stream to START_ARRAY first:
jp.nextToken();
// and then each time, advance to opening START_OBJECT
while (jp.nextToken() == JsonToken.START_OBJECT) {
Map<String,Object> userData = mapper.readValue(jp, Map.class);
userData.get("dayOfWeek");
// process
// after binding, stream points to closing END_OBJECT
}
Make use of Android Volly library as much as possible. It maps your JSON reponse in respective class objects. You can add getter setter for that response model objects. And then you can access these JSON values/parameter using .operator like normal JAVA Object. It makes response handling very simple.

Categories