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.

Nouvel Travay
  • 6,292
  • 13
  • 40
  • 65

8 Answers8

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();
}
Vivek Mishra
  • 5,669
  • 9
  • 46
  • 84
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}

JHoerbst
  • 918
  • 9
  • 17
Navrattan Yadav
  • 1,993
  • 1
  • 17
  • 22
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"}
Anbarasu Chinna
  • 975
  • 9
  • 28
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.

Deepak Bhatia
  • 6,230
  • 2
  • 24
  • 58
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.

Stanley Ko
  • 3,383
  • 3
  • 34
  • 60
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);
Rohit Heera
  • 2,709
  • 2
  • 21
  • 31
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

Shubham Jain
  • 2,365
  • 2
  • 17
  • 29
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;

    }    
}
Tanim reja
  • 2,120
  • 1
  • 16
  • 23