Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Java Object to Json and Vice versa?

I know that JSON object is nothing but the String.

My question is that I have a Map of Object and i want to convert it into Json format.

Example :

Java Class ->
Class Person{
  private String name;
  private String password;
  private int number;
}

Java list ->
Map<List<Long>,List<Person>> map=new HashMap<List<Long>,List<Person>>();
..and map has Some data filled in it.

I want to convert that list into

 Json Format?

How I can achieve it? Because i want to send it over HttpClient... If not what is the other alternative way?

As per my knowledge there is Gson API available, but I dont know how to use it and or in other efficient way.

Thank you

like image 360
Oomph Fortuity Avatar asked Aug 07 '13 14:08

Oomph Fortuity


2 Answers

Not sure what the problem with Gson is. From the doc:

BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 

and

BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);  

That object is (as the name suggests) made up of primitives. However Gson will trivially handle objects, collections of objects etc. Life gets a little more complex when using generics etc., but for your example above I would expect Gson to work with little trouble.

like image 152
Brian Agnew Avatar answered Sep 24 '22 17:09

Brian Agnew


Using Gson to convert to Json using Gson at client side.

Sending String array.

    String[] subscriberArray = new String[]{"eee", "bbb"}; 
    Gson gson = new Gson();
    String recipientInfoStringFormat = gson.toJson(subscriberArray);    

Sending Array of User Defined Type.

        RecipientInfo[] recipientInfos = new RecipientInfo[1];

        RecipientInfo ri = new RecipientInfo();
        ri.setA(1);
        ri.setB("ss");

        recipientInfos.add(ri);

        Gson gson = new Gson();
        String recipientInfoStringFormat = gson.toJson(recipientInfos);     

Using Gson at Server Side to read Data.

For Primitive Types.

            String subscriberArrayParam = req.getParameter("subscriberArrayParam"); 
    Gson gson = new Gson();
    String[] subscriberArray = gson.fromJson(subscriberArrayParam, String[].class);     
    for (String str : subscriberArray) {
        System.out.println("qq :"+str);
    }

For User Defined Object

    String recipientInfos = req.getParameter("recipientInfoStringFormat");

    Gson gson = new Gson();
    RecipientInfo[] ri = gson.fromJson(recipientInfos, RecipientInfo[].class);  
like image 20
Jayesh Avatar answered Sep 25 '22 17:09

Jayesh