Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create json, sorted on keys, using gson?

Tags:

java

json

gson

I need to create constant json string or a json sorted on keys. What do I mean by constant json string? Please look into following code sample, which I created.

My Code 1:

public class GsonTest
{
    class DataObject {

        private int data1 = 100;
        private String data2 = "hello";

    }   


    public static void main(String[] args)
    {
        GsonTest obj=new GsonTest();
        DataObject obj2 = obj.new DataObject();
        Gson gson = new Gson();

        String json = gson.toJson(obj2);
        System.out.println(json);
    }
}

Output 1:

{"data1":100,"data2":"hello"}

My Code 2:

public class GsonTest
{
    class DataObject {
        private String data2 = "hello";
        private int data1 = 100;


    }   


    public static void main(String[] args)
    {
        GsonTest obj=new GsonTest();
        DataObject obj2 = obj.new DataObject();
        Gson gson = new Gson();

        String json = gson.toJson(obj2);
        System.out.println(json);
    }
}

Output 2:

{"data2":"hello","data1":100}

If you see, if I switch variables (data1 & data2 in DataObject class), I get different json. My objective to get same json, even if somebody changes position of the class variables. I get it when somebody adds new variables, json would change. But json shouldn't change when variables are moved around. So, my objective is to get standard json, possibly in sorted keys order for same class. If there is nested json, then it should be sorted in the nested structure.

Expected output on run of both the codes:

{"data1":100,"data2":"hello"}  //sorted on keys!! Here keys are data1 & data2

I understand, I need to change something in String json = gson.toJson(obj2); line, but what do I have to do?

Why I need them to be order?

I need to encode the json string and then pass it to another function. If I change the order of keys, even though value remain intact, the encoded value will change. I want to avoid that.

like image 601
Abhishek Avatar asked May 04 '15 12:05

Abhishek


1 Answers

First of all, the keys of a json object are unordered by definition, see http://json.org/.

If you merely want a json string with ordered keys, you can try deserializing your json into a sorted map, and then serialize the map in order to get the sorted-by-key json string.

GsonTest obj=new GsonTest();
DataObject obj2 = new DataObject();
Gson gson = new Gson();

String json = gson.toJson(obj2);
TreeMap<String, Object> map = gson.fromJson(json, TreeMap.class);
String sortedJson = gson.toJson(map);
like image 75
wings Avatar answered Sep 20 '22 17:09

wings