Gson为Json提供单个键值 [英] single key value to Json with Gson

查看:108
本文介绍了Gson为Json提供单个键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个键值对,我需要使用Gson转换为Json.我该怎么办?说我有

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.

推荐答案

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

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

这篇关于Gson为Json提供单个键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆