我有一个看起来像这样的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
的双引号?
答案 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));
}