java 创建一个没有密钥的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44318500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a JSON without a key
提问by Suraj
We wanted to create a JSON structure as below in Java
我们想在 Java 中创建如下的 JSON 结构
{
[
{
"key": "ABC001",
"value": true
},
{
"key": "ABD12",
"value": false
},
{
"key": "ABC002",
"value": true
},
]
}
To implement this we created a class and had a list private property inside it.
But that is creating a key values
为了实现这一点,我们创建了一个类并在其中包含一个列表私有属性。但这正在创建一个密钥values
class Response{
private List<Property> values;
// setter getter for this private property
}
The output for this is
这个的输出是
{
values : [
{
"key": "ABC001",
"value": true
},
......
]
Is there a way we create the array without the key and inside the { }
?
有没有办法在没有键的情况下创建数组{ }
?
回答by Christian Ascone
Unfortunately, what you're trying to build is not a valid json. You can try to validate it here.
不幸的是,您尝试构建的不是有效的 json。您可以尝试在此处验证它。
With this "json", for example, it would be impossible to read the array, because it has no key.
例如,使用这个“json”,就不可能读取数组,因为它没有键。
{
"foo_key" : "bar",
[
{
"key": "ABC001",
"value": true
},
{
"key": "ABD12",
"value": false
},
{
"key": "ABC002",
"value": true
},
]
}
Parsing a json like this one, you could get "bar" because it has a key ("foo_key"), but how could you get the array?
解析这样的 json,你可以得到“bar”,因为它有一个键(“foo_key”),但是你怎么得到数组呢?
The code you're using is already correct for a valid json.
您使用的代码对于有效的 json 来说已经是正确的。
回答by nonzaprej
So, for some reason you want an invalid json, which is an array contained between {}
s. Here's how you can do it (I'll assume you use google-gson to make and parse jsons, since you didn't include your code):
因此,出于某种原因,您需要一个无效的 json,它是一个包含在{}
s之间的数组。这是您的操作方法(我假设您使用 google-gson 来制作和解析 json,因为您没有包含您的代码):
// example of the creation of the list
List<Property> values = new ArrayList<>();
values.add(new Property("ABC001", true));
values.add(new Property("ABD12", false));
values.add(new Property("ABC002", true));
//
Gson gson = new Gson();
String json = gson.toJson(values, new TypeToken<List<Property>>() {}.getType());
json = "{" + json + "}";// gotta do what you gotta do...