java 无法将 HashSet 解析为 JSONObject 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37962066/
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
Can't parse HashSet to JSONObject String
提问by Ashraful Islam
I am trying to Convert HashSet<String>
to JSONObject
and then Parse the output JSON.
我正在尝试转换HashSet<String>
为JSONObject
然后解析输出 JSON。
Here is what I have tried:
这是我尝试过的:
JSONObject json = new JSONObject();
json.put("set", new HashSet<>(Arrays.asList("a", "b")));
json.put("list", Arrays.asList("a", "b"));
String jsonString = json.toJSONString();
System.out.println(jsonString);
JSONParser parser = new JSONParser();
JSONObject afterParse = (JSONObject) parser.parse(jsonString);
System.out.println(afterParse.toJSONString());
But it's giving me this output and error:
但它给了我这个输出和错误:
{"set":[b, a],"list":["a","b"]}
Exception in thread "main" Unexpected character (b) at position 8.
Here, you can see both a and b are strings, in the list both are inside double quotation marks but in the set it's not.
在这里,您可以看到 a 和 b 都是字符串,在列表中都在双引号内,但在集合中不是。
I am using org.json.simple
v1.1.
我正在使用org.json.simple
v1.1。
采纳答案by Sach141
I think this is a problem with org.json.simple
library.
我认为这是org.json.simple
图书馆的问题。
I have used org.json
library, and have to do some minor changes in above code to work:
我使用过org.json
库,并且必须对上面的代码进行一些小的更改才能工作:
JSONObject json = new JSONObject();
json.put("set", new HashSet<>(Arrays.asList("a", "b")));
json.put("list", Arrays.asList("a", "b"));
String jsonString = json.toString();
System.out.println(jsonString);
JSONObject afterParse = new JSONObject(jsonString);
System.out.println(afterParse.toString());
The output of this code is:
这段代码的输出是:
{"set":["a","b"],"list":["a","b"]}
回答by mattyman
when u convert a array of strings to list and then the list to a Set, it is no longer String, but an array of objects hence new HashSet<>(Arrays.asList("a", "b"))); gives "set":[b, a] (without quotes). And parser.parse(jsonString); works on Object not array of Objects.
当您将字符串数组转换为列表,然后将列表转换为集合时,它不再是字符串,而是一个对象数组,因此 new HashSet<>(Arrays.asList("a", "b"))); 给出 "set":[b, a] (不带引号)。和 parser.parse(jsonString); 适用于对象而不是对象数组。
Try using a list instead of a set as below :
尝试使用列表而不是如下集合:
json.put("set", new Arraylist<>(new HashSet<>(Arrays.asList("a", "b"))));
回答by sarang
The alternative solution is use com.fasterxml.Hymanson.databind.ObjectMapper
替代解决方案是使用 com.fasterxml.Hymanson.databind.ObjectMapper
String str = "str1";
String str2 = "str2";
String str4 = "str3";
Set<String> setObject= new HashSet();
setObject.add(str);
setObject.add(str2);
setObject.add(str4);
ObjectMapper mapperObj = new ObjectMapper();
String JSON = mapperObj.writeValueAsString(setObject);