4

I have single key-value pair that I need to convert to Json using Gson. How might I do that? 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?
  }

}

Notice I am not serializing the whole class: just the two fields.

3
  • you can use getter-setter methods
    – Nisarg
    Dec 22, 2015 at 4:51
  • 1
    why don't you create your json manually instead of using library. JsonObject json=new JsonObject(); json.put(key,value); return json; Dec 22, 2015 at 4:56
  • @VivekMishra do you mind posting as response instead of comment Dec 22, 2015 at 5:20

8 Answers 8

10

why don't you create your json manually instead of using library.

public String singleKeyValueToJson(){
    JSONObject json=new JSONObject();
    json.put(key,value);
    return json.toString();
}
6
  • 3
    According to Gson API version 2.8.1 the updated method is json.addProperty(key, value); Sep 11, 2018 at 6:38
  • @HasanAbdullah I am not using gson in my answer though Sep 11, 2018 at 6:52
  • I see... Sir, What is the package name for JsonObject? Sep 11, 2018 at 9:21
  • 1
    @HasanAbdullah I typed that manually at that time so forgot about the casing.I have now corrected it. Sep 11, 2018 at 9:22
  • dont just use a random extra library. The question was asked using Gson, dont just switch to SimpleJson because you dont like Gson Jun 4, 2022 at 5:04
3

you can do that using @Expose annotation.

import com.google.gson.annotations.Expose;

public class Book {

    @Expose
    private String author;
    @Expose
    private String title;
    private Integer year;
    private Double price;

    public Book() {
        this("test.org", "Exclude properties with Gson", 1989, 49.55);
    }

    public Book(String author, String title, Integer year, Double price) {
        this.author = author;
        this.title = title;
        this.year = year;
        this.price = price;
    }
}

.

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class WriteGson {

    public static void main(String[] args) {

        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .create();

        String json = gson.toJson(new Book());
        System.out.println(json);

        Gson gsonNonExcluded = new Gson();
        String jsonNonExcluded = gsonNonExcluded.toJson(new Book());
        System.out.println(jsonNonExcluded);
    }
}

{"author":"test.org","title":"Exclude properties with Gson"} {"author":"test.org","title":"Exclude properties with Gson","year":1989,"price":49.55}

2

Consider your class having 3 variable and a method to return JSONObject of the only 2 variables, like follows

class MyClass{
    String _value1 = "1234";
    int _value2 = 9100;
    String _value3 = "5678";

    public String singleKeyValueToJson(){
        //add only selected variables to holder object(here HashMap),
        HashMap<String,Object> map = new HashMap();
        map.put("key1",_value1);
        map.put("key2",_value2);
        //convert holder object to JSONObject directly and return as string as follows
        return new Gson().toJson(map);
    }
}

never forget to add Gson lib to your project,when you call that method will return JSONObject as String like

    {"key2":9100,"key1":"1234"}
1

I use the google GSON library com.google.gson.Gson and the code will be simple and straight
As you just wanna to serailize the key-value for it SimpleEntry is best class and you can do it as,

    public String singleKeyValueToJson()
    {
        Gson jsonObj = new Gson();
        SimpleEntry<String,String > keyValue = new SimpleEntry<String, String>(this.key, this.value);
        return jsonObj.toJson(keyValue);
    }

EDIT
You can make improvements in memory utilization by using single instance of Gson object if you are serializing very often or many times.

1
  • For me this is serializing as {"key": "foo", "value": "bar"} when I need {"foo": "bar"} ... Nov 24, 2021 at 21:48
0

You can use gson like below:

public class MyClass {

    private static final Gson gson = new Gson();

    String key;
    String value;

    public String singleKeyValueToJson() {
        return gson.toJson(this);
    }

}

Note that Gson is static, for reduce overhead and it is final, for prevent create another Gson instance.

0
For gson u can write like this


public class MyClass {
    String key;
    public MyClass(String value) {
        this.key = value;
    }
    public String getKey() {
        return key;
    }

    public void setKey(String value) {
        this.key = value;
    }
}


Gson gson = new Gson();

MyClass data = new MyClass("ValueData");

String requestString = gson.toJson(data);
0
class A {
public String key;
public String value;

public String singleKeyValueToJson() {
        A als = new A();
        als.key= "text1";
        als.value= "text2";
        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();
        return gson.toJson(als);    
    }
}

and it will return single key value to Json with Gson

0

just trying to manually create json data. getJsonData() this method will return json.

import org.json.JSONException;
import org.json.JSONObject;    

class MyClass{
     private String key;
     private String value;

    public String getkey() {
            return key;
    }

    public void setkey(String key) {
            this.key = key;
    }    

    public String getValue() {
            return value;
    }

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


    public JSONObject getJsonData(){

    JSONObject jsonObject = new JSONObject();

    try {
        jsonObject.put(getKey(), getValue());

    } catch (JSONException e) {
            e.printStackTrace();
    }
    return jsonObject;

    }    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.