Converting JSON to Hashmap<String, POJO> using GWT

1.2k views Asked by At
SortedMap<String, VehicleData> hmap = new TreeMap<String, VehicleData>();

My JSON String sample:

 {
    "3": {
        "Field1": 12,
        "Field2": "value",
        "Field3": null
    },
    "test": {
        "Field1": 20,
        "Field2": "value",
        "Field3": "vit"
    }
}

I want to convert this string to HashMap declared above. Is there any method to convert directly from Json string to Hashmap?

1

There are 1 answers

4
Asif Bhutto On

using Gson you can parse it eailsy at server side.

Gson gson = new Gson();
Type type= new TypeToken<Map<String, VehicleData>>(){}.getType();
Map<String,VehicleData> map = gson.fromJson(Your_JSON_STRING, type);

If you want client/server side serialize/deserialize JSON in GWT code.

In GWT 2.1.1 you can use GWT AutoBean framework

String serializeToJson(Test test) 
{
    // Retrieve the AutoBean controller
    AutoBean<Test> bean = AutoBeanUtils.getAutoBean(test);
    return AutoBeanCodex.encode(bean).getPayload();
}

Test deserializeFromJson(String json) 
{     
    AutoBean<Test> bean = AutoBeanCodex.decode(myFactory, Test.class, json);     
    return bean.as();   
} 

I've not tried with complex and low level with Map, you can go with doc

Finally if you want to gson on client side with GWT then you have to try bGwtGson library