0

I am working on jquery datatable plugin with wiki rest service. I am stuck at, to convert string like structure as follows

[{"name":"sEcho","value":1},{"name":"iColumns","value":5}]

into map of objects. like ::

{"sEcho"=1, "iColumns"=5, "bSearchable_4"=true, "sSearch_3"="", "bRegex_3"=false, "mDataProp_3"=3, "sSearch_1"="", "bSortable_0"=true, "bRegex_1"=false}

Question is, Is there any generic way or library to do?

I am tried the fallowing -

       queryJson = queryJson.replace("[", "");
       queryJson = queryJson.replace("]", "");
       String[] params =  queryJson.split("},");

       Map<String, Object> paramMap = new HashMap<String, Object>();

       for(int i=0;i<params.length-1;i++){
           String[] curObj = params[i].split(":");
           String[] keyObj = curObj[1].split(",");                     
           paramMap.put(keyObj[0], curObj[2]);                     
       }

Getting output. But i think there might be better way to do. Please suggest me any library or generic way to do this. Thanks

Darshit Chokshi
  • 589
  • 3
  • 13
Ramesh Papaganti
  • 7,311
  • 3
  • 31
  • 36

2 Answers2

0

See this, Hope this will work for you -

import java.util.HashMap;
import java.util.Map;

import com.google.gson.Gson;

public class Stack {

    public static void main(String[] args) {

        String jsonResponse = "[{\"name\":\"sEcho\",\"value\":1},{\"name\":\"iColumns\",\"value\":5}]";

        Gson gson = new Gson();

        //Parse json into a JsonResponseData object.
        JsonResponseData[] jsonResponseData = gson.fromJson(jsonResponse, JsonResponseData[].class);

        Map<String, Object> paramMap = new HashMap<String, Object>();

        for(JsonResponseData data : jsonResponseData){
            paramMap.put(data.getName(), data.getValue());
        }

        System.out.println(paramMap);
    }
}

public class JsonResponseData {

    private String name;

    private Object value;

    public JsonResponseData(String name, Object value) {
        super();
        this.name = name;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }

}
Darshit Chokshi
  • 589
  • 3
  • 13
0

Use JSONObject something like this.

HashMap<String, String> paramMap = new HashMap<String, String>();
for (int i = 0; i < params.length(); i++) {
   JSONObject jObj = params.optJSONObject(i);
   Iterator it = jObj.keys();
   while (it.hasNext()) {
      String n = it.next();
      paramMap.put(n, jObj.getString(n));
   }
}
Durgpal Singh
  • 11,481
  • 4
  • 37
  • 49