使用Gson将单键值转为Json

问题描述 投票:0回答:8

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

}

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

java android json gson
8个回答
10
投票

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

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

3
投票

您可以使用 @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":"使用 Gson 排除属性"} {"author":"test.org","title":"排除带有 Gson 的属性","year":1989,"price":49.55}


2
投票

考虑您的类有 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 lib 添加到你的项目中,当你调用该方法时将返回 JSONObject 作为字符串

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

1
投票

我使用谷歌GSON库

com.google.gson.Gson
,代码会简单直接
因为你只是想序列化它的 key-value
SimpleEntry
是最好的类,你可以这样做,

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

编辑
如果您经常或多次序列化,则可以通过使用

Gson
对象的单个实例来提高内存利用率。


0
投票

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

public class MyClass {

    private static final Gson gson = new Gson();

    String key;
    String value;

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

}

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


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

它将用Gson返回单个键值到Json


0
投票

只是尝试手动创建 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;

    }    
}
© www.soinside.com 2019 - 2024. All rights reserved.