0

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!

Community
  • 1
  • 1
Aleksey Kiselev
  • 331
  • 1
  • 7
  • 21

2 Answers2

0

Create a Friend class which has fields for email, id, firstName, lastName, etc. Populate a collection object with Friend class instances. Serialize the collection.

NicoE
  • 186
  • 7
0

Serializing and Deserializing JSON objects are quite easy when you use some existing libraries (why to re-invent wheel?). What you could improve is to use gson - Google's library for working with json. I will explain how it works:-

Create a Friend Class with all the fields you require.

Class Friend{
  String email;
  String firstName;
  Integer id;
  String lastName;

  Friend(String email,String firstName,Integer id,String lastName){
    this.email = email;
    this.firstName = firstName;
    this.id = id;
    this.lastName = lastName;
  //This is Constructor
  }
}

Create a class for you enclosing JSON Object friends:

Class Friends{
  Friend[] friend;

  Friends(Friend[] friend){
     this.friend = friend;
  }
}

Now say obj is of type Friends. You will simple get the JSON string by:

import com.google.gson.Gson;
Gson gson = new Gson();
String jsonInString = gson.toJson(obj);

References: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

Let me know if you still have trouble making it work!

Mangat Rai Modi
  • 5,397
  • 8
  • 45
  • 75
  • Mangat, I implemented 2 separate classes as you described. But the problem is - I got code: `import com.google.gson.*; public class Gson { public static void main(String[] args) { Friend friend = new Friend(); friend.setEmail("email"); friend.setFirstName("first"); friend.setLastName("last"); friend.setId(2); Gson gson = new Gson(); String json = gson.toJson(friend); } }` but I got an error here: at *toJson* I got an error - The method toJson(Friend) is undefined for the type Gson. I'm using gson-2.6.2.jar library. Thank you! – Aleksey Kiselev May 13 '16 at 00:13
  • You don't need to create the Gson jar. Its already imported by import com.google.gson.Gson; When you created Gson class, it has masked the original Gson class from google – Mangat Rai Modi May 13 '16 at 03:54
  • Oh, I got it (I made it by mistake, just decided that this gonna be a good name for my class).. Thank you, Mangat – Aleksey Kiselev May 13 '16 at 17:19
  • Just one last thing - how could I add top level "Friend" tag in this code: `public class jsonnew { public static void main(String[] args) { //Friends friends = new Friends(null); List friends = new ArrayList(); for (int i = 0; i < 3; i++) { Friend friend = new Friend(); friend.setEmail("email"); friend.setFirstName("first"); friend.setLastName("last"); friend.setId(i); friends.add(friend); } Gson gson = new Gson(); String json = gson.toJson(friends); System.out.println(json); } }` Thank you! – Aleksey Kiselev May 14 '16 at 01:01