使用Gson构建一个JSON对象,其中值不应该有引号

时间:2017-05-26 07:51:25

标签: java json gson

我有一个看起来像这样的JSON:

{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": [{
    "key11": {
        "key21": "value21"
    }
}, {
    "key12": "value12"
}]
}

并且需要为key4中的每个值获取JSON。

{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": {
    "key11": {
        "key21": "value21"
    }
}
}

{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": {
    "key12": "value12"
}
}

但我的输出如下:

{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "{\"key11\": {\"key21\": \"value21\"}}"
}

我正在使用JSON构建器并将Java对象转换为JSON对象。

public class BuildJson {
    private String key1 = "value1";
    private String key2 = "value2";
    private String key3 = "value3"; 
    private String key4;

public BuildJson(String value4) {       
    key4 = value4;
}

public String buildJson(BuildJson bj){      
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String new_json = gson.toJson(bj);
    return new_json;        
}
}

初始化构造函数并调用buildJson方法。

List <String> key4_object; //holds list of values
for (String i : key4_object){
    BuildJson bj = new BuildJson(i);
    String new_json = bj.buildJson(bj);
    System.out.print(gson.toJson(new_json));
}

由于key4属于String类型,因此它会添加引号,值始终为String

如何避免key4的双引号?

1 个答案:

答案 0 :(得分:1)

不要成为String。这是唯一的方法;没有逃避和双引String将是一个错误和破坏的行为。

问题是在所有3种情况下,你在这个密钥下都有不同结构的JSON,所以不清楚它应该是什么类型。你可以简单地做到JsonElement key4

public class BuildJson {
    private String key1 = "value1";
    private String key2 = "value2";
    private String key3 = "value3"; 
    private JsonElement key4;

public BuildJson(Object value4) {       
    key4 = new Gson().toJsonTree(value4);
}

public String buildJson(){      
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String new_json = gson.toJson(this);
    return new_json;
}
}

假设String中的key4_object是您想要的对象的JSON,

List<String> key4_object = ...;
JsonParser parser = new JsonParser();
for (String i : key4_object){
    BuildJson bj = new BuildJson(parser.parse(i));
    String new_json = bj.buildJson();
    System.out.print(gson.toJson(new_json));
}