【问题标题】:single key value to Json with Gson带有 Gson 的 Json 的单键值
【发布时间】:2015-12-22 04:46:40
【问题描述】:

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

}

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

【问题讨论】:

  • 你可以使用getter-setter方法
  • 为什么不手动创建 json 而不是使用库。 JsonObject json=new JsonObject(); json.put(键,值);返回 json;
  • @VivekMishra 你介意发布作为回复而不是评论

标签: java android json gson


【解决方案1】:

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

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

【讨论】:

  • 根据Gson API version 2.8.1更新的方法是json.addProperty(key, value);
  • @HasanAbdullah 我没有在我的回答中使用 gson
  • 我明白了...先生,JsonObject 的包名是什么?
  • @HasanAbdullah 我当时是手动输入的,所以忘记了大小写。我现在已经更正了。
【解决方案2】:

您可以使用@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}

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      我使用谷歌GSON库com.google.gson.Gson,代码会简单直接
      因为您只想为它的 key-value 进行 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);
          }
      

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

      【讨论】:

      • 当我需要 {"foo": "bar"} ...
      【解决方案5】:

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

      public class MyClass {
      
          private static final Gson gson = new Gson();
      
          String key;
          String value;
      
          public String singleKeyValueToJson() {
              return gson.toJson(this);
          }
      
      }
      

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

      【讨论】:

        【解决方案6】:
        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);
        

        【讨论】:

          【解决方案7】:
          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

          【讨论】:

            【解决方案8】:

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

            【讨论】:

              猜你喜欢
              • 2013-11-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2014-02-12
              • 1970-01-01
              • 2014-04-26
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多