I'm new in Java and JSON and I'm trying to form JSON for my rest api (I previously used XML and converter cause I'm using AngularJS, but I would like to form JSON without conversioning). The format of the JSON should be:
{
"friends": {
"friend": [
{
"email": "aa@aa.aa",
"firstName": "aa",
"id": "31",
"lastName": "aa"
},
{
"email": "bb@bb.bb",
"firstName": "bb",
"id": "32",
"lastName": "bb"
}
]
}
}
The problem is (I googled a lot, and the best article is - Java & Json: Wrapping elements when serialising) but in the example - I got only one row in the lower level and if I'm using something like this:
public class JsonSimpleExample {
public static void main(String[] args) {
org.json.simple.JSONObject jsonObject3=new org.json.simple.JSONObject();
org.json.simple.JSONObject jsonObject2=new org.json.simple.JSONObject();
for (int j = 0; j < 4; j++) {
org.json.simple.JSONObject jsonObject=new org.json.simple.JSONObject();
Map<String, Object> data = new HashMap<String, Object>();
data.put("email","aa@aa.aa");
data.put("firstName","aa");
data.put("lastName","aa");
data.put("id",j);
JSONObject json = new JSONObject();
json.putAll( data );
jsonObject2.put("friend",json);
jsonObject3.put("friends",jsonObject2);
}
System.out.print(jsonObject3);
}
Here I got only the last row, what is obvious. For the other hand - while I'm using HashMap or Map - I got a little bit different format. May be I should use something from this example (I mean List), but not sure how it finally should be: https://stackoverflow.com/questions/27743227/creating-parent-property-in-json. So, I implemented it this way:
public class JsonSimpleExample {
public static void main(String[] args) {
org.json.simple.JSONObject jsonObject3=new org.json.simple.JSONObject();
org.json.simple.JSONObject jsonObject2=new org.json.simple.JSONObject();
JSONArray arr = new JSONArray();
HashMap<String, JSONObject> map = new HashMap<String, JSONObject>();
for(int i = 0 ; i < 10 ; i++) {
JSONObject data=new JSONObject();
data.put("email","aa@aa.aa"+i);
data.put("firstName","aa");
data.put("lastName","aa");
data.put("id",i);
map.put("json" + i, data);
arr.put(map.get("json" + i));
}
jsonObject2.put("friend",arr);
jsonObject3.put("friends",jsonObject2);
System.out.print(jsonObject3);
}
}
I don't care for right now about how to generate JSON (I mean - using Jackson, Pojo or something else), my main problem is to understand - if I'm on the right way on getting the same data format as I had after XML to JSON data conversion. And what could I improve in my code?
Thank you!