Java 使用Gson将单个键值转换为Json

Java 使用Gson将单个键值转换为Json,java,android,json,gson,Java,Android,Json,Gson,我需要使用Gson将单个键值对转换为Json。我该怎么做?说我有 class MyClass{ String key; String value; ...//bunch of other fields public String singleKeyValueToJson(){ return new Gson(key,value);//how do I do this? } } 请注意,我没有序列化整个类:只序列化了两个字段。您可以使用gson,如下所示: pub

我需要使用Gson将单个键值对转换为Json。我该怎么做?说我有

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

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

}

请注意,我没有序列化整个类:只序列化了两个字段。

您可以使用gson,如下所示:

public class MyClass {

    private static final Gson gson = new Gson();

    String key;
    String value;

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

}

请注意,为了减少开销,Gson是静态的,为了防止创建另一个Gson实例,它是最终的。

我使用google Gson库
com.google.Gson.Gson
,代码将简单明了
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);
因为您只想序列化键值,因为
SimpleEntry
是最好的类,您可以这样做

    public String singleKeyValueToJson()
    {
        Gson jsonObj = new Gson();
        SimpleEntry<String,String > keyValue = new SimpleEntry<String, String>(this.key, this.value);
        return jsonObj.toJson(keyValue);
    }
公共字符串singleKeyValueToJson()
{
Gson jsonObj=新的Gson();
SimpleEntry keyValue=新的SimpleEntry(this.key,this.value);
返回jsonObj.toJson(keyValue);
}
编辑

如果要经常或多次序列化,可以使用
Gson
对象的单个实例来提高内存利用率

为什么不手动创建json而不是使用库呢

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

假设您的类有3个变量和一个只返回2个变量的JSONObject的方法,如下所示

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);
    }
}

它将通过Gson向Json返回单个键值,只需手动创建Json数据
getJsonData()
此方法将返回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;

    }    
}
您可以使用注释来实现这一点

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;
    }
}

{“author”:“test.org”,“title”:“使用Gson排除属性”}
{“author”:“test.org”,“title”:“使用Gson排除属性”,“year”:1989,“price”:49.55}

您可以使用getter setter方法为什么不手动创建json而不使用库呢。JsonObject json=新的JsonObject();put(key,value);返回json@VivekMishra根据更新后的方法是
json.addProperty(key,value),您介意以响应而不是评论的形式发布吗@HasanAbdullah我的答案中没有使用gson,尽管我明白了。。。先生,JsonObject的包名是什么?@HasanAbdullah当时我是手动输入的,所以忘记了大小写。我现在已经更正了。
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;

    }    
}
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);
    }
}