Hunt
Hunt

Reputation: 8435

convert key's value as a key in json using GSON

I am generating following JSON using GSON library

[
  {
    "name": "Mobile Number",
    "value": "234567891"
  },
  {
    "name": "Controller Number",
    "value": "I1500001"
  },
  {
    "name": "Unit Type",
    "value": "2"
  },
  {
    "name": "Operator",
    "value": "32"
  },
  {
    "name": "Data Length",
    "value": "0"
  },
  {
    "name": "Software Version",
    "value": "32"
  },
  {
    "name": "Mode",
    "value": "6"
  }
]

My class has two fields as follows

public class IDUData {

        @SerializedName("name")
        private String name;
        @SerializedName("value")
        private String value;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    }

now what i want to do is to generate JSON in following forma.i want my name key field's value to be a key. the reason why i am using this approach is in future if new name key is added , my expected json will automatically has a key.

[
  {
    "Mobile Number": "234567891"
  },
  {
    "Controller Number": "I1500001"
  },
  {
    "Unit Type": "2"
  },
  {
    "Operator": "32"
  },
  {
    "Data Length": "0"
  },
  {
    "Software Version": "32"
  },
  {
    "Mode": "6"
  }
]

Upvotes: 0

Views: 229

Answers (3)

Kushal
Kushal

Reputation: 8508

You can write code suggested by @wblaschko in onResponse() if you have used Volley library :

final GsonRequest gsonRequest = new GsonRequest(URL /* your URL */,
      IDUData.class, null, new Response.Listener<IDUData>() {

    @Override
    public void onResponse(IDUData data) {
        // Copy code here
        HashMap<String, String> map = new HashMap<>();
        for(IDUData data: list){
            map.put(data.getName(), data.getValue());
        }
        String output = new Gson().toJson(map);
        // Copy code here
     }, new Response.ErrorListener() {

     }
}

Upvotes: 0

Randyka Yudhistira
Randyka Yudhistira

Reputation: 3652

Use gson JsonParser

String mJsonString = "{
    \"name\": \"Controller Number\",
    \"value\": \"I1500001\"
  }";
JsonElement mJson =  new JsonParser.parse(mJsonString);

IDUData object = gson.fromJson(mJson, IDUData.class);

Upvotes: 0

wblaschko
wblaschko

Reputation: 3262

What you want to do is create a HashMap out of the data first. The code below should be pretty close, once you've either made a List or an array out of the IDUData items:

List<IDUData> list = ...; // or IDUData[] list = ...;
HashMap<String, String> map = new HashMap<>();
for(IDUData data: list){
    map.put(data.getName(), data.getValue());
}
String output = new Gson().toJson(map);

Upvotes: 1

Related Questions