Java – Use a single key value from Gson to Json

Use a single key value from Gson to Json… here is a solution to the problem.

Use a single key value from Gson to Json

I

have a key-value pair and I need to convert it to JSON using gson. What should I do? Say I have

class MyClass{
  String key;
  String value;
  ...//bunch of other fields

public String singleKeyValueToJson(){
    return new Gson(key,value);//how do I do this?
  }

}

Note that I’m not serializing the entire class: just two fields.

Solution

Why not create JSON manually instead of using libraries.

public String singleKeyValueToJson(){
    JSONObject json=new JSONObject();
    json.put(key,value);
    return json.toString();
}

Related Problems and Solutions