java 使用 Gson 到 Json 的单个键值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34408579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 22:51:54  来源:igfitidea点击:

single key value to Json with Gson

javaandroidjsongson

提问by Nouvel Travay

I have single key-value pair that I need to convert to Json using Gson. How might I do that? Say I have

我有一个键值对,我需要使用 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?
  }

}

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

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

回答by Vivek Mishra

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

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

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

回答by Navrattan Yadav

you can do that using @Exposeannotation.

你可以使用@Expose注释来做到这一点

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}

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

回答by Anbarasu Chinna

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

考虑你的类有 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);
    }
}

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

永远不要忘记将 Gson 库添加到您的项目中,当您调用该方法时,将像 String 一样返回 JSONObject

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

回答by dbw

I use the google GSON library com.google.gson.Gsonand the code will be simple and straight
As you just wanna to serailize the key-valuefor it SimpleEntryis best class and you can do it as,

我用的是谷歌GSON库com.google.gson.Gson,代码将是简单而直接
当你只想以serailize的键值为它SimpleEntry是最好的班,你能做到这一点的,

    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 Gsonobject if you are serializing very often or many times.

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

回答by Stanley Kou

You can use gson like below:

您可以像下面这样使用 gson:

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.

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

回答by Rohit Heera

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

回答by Shubham Jain

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

它将使用 Gson 将单个键值返回给 Json

回答by Tanim reja

just trying to manually create json data. getJsonData()this method will return 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;

    }    
}