[英]How to add values at JSONObject in Java?
I added values using like json.put("key", "value")
. 我使用json.put("key", "value")
来添加值。
The result was {"key": "value"}
. 结果是{"key": "value"}
。
But I want to get result like {key: "value"}
但我想得到类似{key: "value"}
How do I do? 我该怎么办?
That is not possible as JSON Objects' keys are always enclosed in quotes. 这是不可能的,因为JSON对象的键始终用引号引起来。 The values can have no quotes if it's Booloean or number like : 如果值是Booloean或类似数字的值,则不能使用引号:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"height_cm": 167.6
}
Json uses quotes to increase the posible types of key and value. Json使用引号来增加键和值的可能类型。
Example: 例:
{ Some key : Some Vaue } - Invalid {Some key:Some Vaue}-无效
{ Some key : Some : Vaue } - Invalid {Some key:Some:Vaue}-无效
This is not a valid JSON as any Json parser will fail to identify the "space" between words. 这不是有效的JSON,因为任何Json解析器都无法识别单词之间的“空格”。 In order to avoid such situations, JSON objects are defined with quotes. 为了避免这种情况,JSON对象用引号定义。
{ "Some key" : "Some : Vaue" } - This is valid {“ Some key”:“ Some:Vaue”}-这是有效的
This is the reason for any JSON parser to return the key and values quoted. 这就是任何JSON解析器返回键和引用值的原因。
An example to help you 一个可以帮助你的例子
public static void main(String[] args)
{
Gson gson = new Gson();
//String json = "{key : \"value\"}"; - Valid
//String json = "{key : value}"; - Valid
//String json = "{key : some : value}"; // Invalid
String json = "{key : \"some : value\"}"; // Valid
Map<String, String> map = gson.fromJson(json, Map.class);
System.out.println(map.size());
System.out.println(gson.toJson(map));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.