create a JSON file in java with array - java

I use JSON-simple-1.1.1 and I want to create a JSON file like this:
{
"data": [
[
"1",
"YES",
"sp_1",
"1",
"xxx"
],
[
"2",
"NO",
"sp_2",
"2",
"yyyy"
],
[
"3",
"YES",
"sp_3",
"2",
"zzzz"
]
]
}
I try to use JSONObject and JSONArray but I cannot resolve how to create a multi array like above

A little helper makes life easier:
public static JSONArray jsonArray(Object... values) {
JSONArray arr = new JSONArray();
arr.addAll(Arrays.asList(values));
return arr;
}
Then:
JSONObject obj = new JSONObject();
obj.put("data", jsonArray(jsonArray("1", "YES", "sp_1", "1", "xxx"),
jsonArray("2", "NO" , "sp_2", "2", "yyyy"),
jsonArray("3", "YES", "sp_3", "2", "zzzz")));
System.out.println(obj.toJSONString());
Output
{"data":[["1","YES","sp_1","1","xxx"],["2","NO","sp_2","2","yyyy"],["3","YES","sp_3","2","zzzz"]]}

My Questions is bad write. I don't explain that read row from database and for that I don't know how many row found. the inside array is dinamic.
With Andreas help i found this solution:
public static JSONArray jsonArray(Object... values) {
JSONArray arr = new JSONArray();
arr.addAll(Arrays.asList(values));
return arr;
}
then:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// loop to database row. To simplify code example write some database row found...
ja.add(jsonArray("1", "YES", "sp_1", "1", "xxx"));
ja.add(jsonArray("2", "YES", "sp_1", "1", "xxx"));
ja.add(jsonArray("3", "YES", "sp_1", "1", "xxx"));
jo.put("data", ja );
System.out.print(jo);
Output:
{"data":[["1","YES","sp_1","1","xxx"],["2","YES","sp_1","1","xxx"],["3","YES","sp_1","1","xxx"]]}
Thank to all and sorry for my not clear question.

Related

how to get array of objects from server

I'm trying to have a list of objects from a server. But I don't know how to do it exactly and at least print it in System.out.print
server sends data like that:
[
{
"userId": "15",
"routeId": "10",
"driverId": "2",
"text": "ytf",
"timestamp": "2018-05-25 13:04:01"
},
{
"userId": "15",
"routeId": "33",
"driverId": "2",
"text": "asd",
"timestamp": "2018-05-25 13:07:40"
}
]
And model:
https://pastebin.com/52mc5Gmw
https://pastebin.com/DnUTtkPC
Controller: https://pastebin.com/ucJFFJyy
And the API:
#GET("getReviews.php")
Call<List<reviewResult>> getReview();
You can use JSONArray for parse the array, and JSONObject for get each object of the array
Edit Add a example
JSONArray jsonArray = new JSONArray(response);
for(int i=0; i<jsonArray.length();i++)
{
JSONObject object = jsonArray.getJSONObject(i);
System.out.print(object);
}
From your code, looks like the expected return type should be List of reviewResponse objects. You should change the API to:
Call<List<reviewResponse>> getReview();
From there it's obvious how to retrieve the data you ask

Parse a complex JSON result

I have a json (result) like the below , i need the value of Key "extra", that is "contact office".
I tried the below code, but it did not work, can you help?
JSONArray jsonArray = new JSONArray(result.toString().trim());
JSONObject json = jsonArray.getJSONObject(0).getJSONObject("student").getJSONArray("department").getJSONObject(0).getJSONObject("classes");
String val=json.getString("extra");
// JSON Example
{
"student": [
{
"department" : [
{
"classes" : [
{
"grade" : "A",
"fine" : "No"
},
{
"grade" : "B",
"fine" : "Yes",
"extra" : "contact office"
},
{
"grade" : "C",
"fine" : "NA"
}
],
}
],
}
],
}
You mixed up JSONArray and JSONObject a few times, not sure exactly what I had to change but the following will work:
JSONObject jsonObject = new JSONObject(result.toString().trim());
JSONArray jsonArray = jsonObject
.getJSONArray("student").getJSONObject(0).getJSONArray("department").getJSONObject(0)
.getJSONArray("classes");
String val = jsonArray.getJSONObject(1).getString("extra");
Is this a full sample? If so it doesn't start out as an array. Student is and object not an array. If it is just a sample of one item in the array then you're okay.
The second thing I noticed is: getJSONObject("classes"). Classes is an array not an object, this won't work.
Would you like to consider using JsonPath. You could do something like this -
String[] extraValues = JsonPath.read(json, "$.student[0].department[0].classes[*].extra");

Not getting JSON data in the order in which i have entered

I am fetching details from a database table which contains 3 rows in JAVA.
I am using JSONarray and JSONObject as follows
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
JSONArray ja=new JSONArray();
The data from table is put to the jsonObject as follows for each one:
String qry="select * from details";
ResultSet res = select .executeQuery(qry);
while(res.next){
String Name=res.getString("name");
String age=res.getString("age");
.
.
jsonObject.put("Name", Name);
jsonObject.put("age", age);
.
.
ja.put(jsonObject);
}
mainjsonObject.put("PERSONAL DETAILS",ja);
I should get the output json as follows(i.e. the order in which i entered):
{
"PERSONAL DETAILS": [
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
},
{
" name": "xyz",
"age": "3",
"gender": "M",
"Place": "abc2"
}
]
}
But am getting the values in random order like below:
{
"PERSONAL DETAILS": [
{
"age": "4",
" name": "abc",
"Place": "abc1"
"gender": "F",
},
{
"age": "3",
" name": "xyz",
"Place": "abc2"
"gender": "M",
}
]
}
Please help me with a solution. I need to get all the values in the same order in which i have entered.
You can try something like this to build json object construct using LinkedHashMap and then pass it to the constructor like this ,
LinkedHashMap<String, String> jsonOrderedMap = new LinkedHashMap<String, String>();
jsonOrderedMap.put("Name", res.getString(1));
...
...
// struct you want
JSONObject JSONorder = new JSONObject(jsonOrderedMap);
JSONArray sortedJSON = new JSONArray(Arrays.asList(JSONorder));

JSON: Get list of JSON Objects

In java how can I pull out the JSON objects enclosed in the "{}"?
I have tried:
JSONObject obj = new JSONObject(jstring);
obj.getJSONArray("fileName");
But it only return the first object. How do I get a list with both objects?
JSON:
[
{
"fileName": [
"file1"
],
"date": [
"8/25/2015 0:00"
],
"time": [
"7/16/2009 16:51"
],
"id": "1",
"version_": 1
},
{
"fileName": [
"file1"
],
"date": [
"8/25/2015 0:00"
],
"time": [
"7/16/2009 16:51"
],
"id": "1",
"version_": 1
}
]
Your root JSON is an Array, so first create a JSONArray from your String.
Do this:
JSONArray arr = new JSONArray(jstring);
for (int i = 0; i < arr.length(); i++) { // Walk through the Array.
JSONObject obj = arr.getJSONObject(i);
JSONArray arr2 = obj.getJSONArray("fileName");
// Do whatever.
}
For more info, please refer to the docs on JSONArray and JSONObject.
You have to directly construct JSONArray from JSON string in this case.
JSONArray arr = new JSONArray(jstring);
JSONArray jsonArray = new JSONArray(jstring);

How do i refactor one JSON array into other format in JAVA?

I have a JSON array like this,
JSONArray content=
"[
{"+"\"pageid\":\"19\","+"\"company\":"+"\"C1\","+"\"pageview\":"+"\"10\","+"\"visitfreq\":"+"\"2\"},{"+"\"pageid\":\"19\","+"\"company\":"+"\"C2\","+"\"pageview\":"+"\"20\","+"\"visitfreq\":"+"\"4\"},{"+"\"pageid\":\"200\","+"\"company\":"+"\"C3\","+"\"pageview\":"+"\"30\","+"\"visitfreq\":"+"\"3\"}
]";
Code for JSONArray:
JSONObject jObj1 = new JSONObject();
jObj1.put("pageid", "19");
jObj1.put("company", "C1");
jObj1.put("pageview", "10");
jObj1.put("visitfreq", "2");
JSONObject jObj2 = new JSONObject();
jObj2.put("pageid", "19");
jObj2.put("company", "C2");
jObj2.put("pageview", "20");
jObj2.put("visitfreq", "4");
JSONObject jObj3 = new JSONObject();
jObj3.put("pageid", "200");
jObj3.put("company", "C3");
jObj3.put("pageview", "30");
jObj3.put("visitfreq", "3");
JSONArray jArr = new JSONArray();
jArr.put(jObj1);
jArr.put(jObj2);
jArr.put(jObj3);
Visual representation:
[
{
"company": "C1",
"visitfreq": "2",
"pageview": "10",
"pageid": "19"
},
{
"company": "C2",
"visitfreq": "4",
"pageview": "20",
"pageid": "19"
},
{
"company": "C3",
"visitfreq": "3",
"pageview": "30",
"pageid": "200"
}
]
I have worked on it to get an out put like below
the out put like this
[{pageid},[{rest of details}] ,{pageid},[{rest of details}] ]
if same pageid occur more than once
it should be like this
[{pageid},[{rest of details1},{rest of details2},.. ],{pageid},[{rest of details}] ]
Looks like you need to create a Map that maps pageid : [{rest of details1},{rest of details2},.. ].
Once you have that Map, you can transform it into your desired output.
Here is the code that will take your JSONArray (the one in the code above) and turn it into Map<String, JSONArray>.
public Map<String, JSONArray> getJsonArrayAsMapOnPageId(JSONArray inputArr) throws JSONException {
//Map holding pageid : [{company:"",pageview:"",visitfreq:""}, ... , ...] mappings
Map<String, JSONArray> idMap = new HashMap<String, JSONArray>();
for (int i=0; i < inputArr.length(); i++) {
JSONObject inputObj = inputArr.getJSONObject(i);
String id = inputObj.getString("pageid");
JSONArray jObjList;
if (idMap.containsKey(id)) {
//append to existing list in the Map
jObjList = idMap.get(id);
} else {
//create new list
jObjList = new JSONArray();
}
JSONObject newJsonObj = new JSONObject();
newJsonObj.put("company", inputObj.get("company"));
newJsonObj.put("pageview", inputObj.get("pageview"));
newJsonObj.put("visitfreq", inputObj.get("visitfreq"));
jObjList.put(newJsonObj);
idMap.put(id, jObjList);
}
return idMap;
}
Here is what it'll look like:
System.out.println("Map looks like:\n" + pageidMap);
Here is what I got:
{
200=[
{
"company": "C3",
"visitfreq": "3",
"pageview": "30"
}
],
19=[
{
"company": "C1",
"visitfreq": "2",
"pageview": "10"
},
{
"company": "C2",
"visitfreq": "4",
"pageview": "20"
}
]
}
I'm not sure exactly in what form (Object, print to output, etc) you want this output to be in, so you can do the final bit of transforming this Map<String, JSONArray> into [{pageid},[{rest of details1},{rest of details2},.. ],{pageid},[{rest of details}] ] without problems.

Categories