Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't parse HashSet to JSONObject String

Tags:

java

json

I am trying to Convert HashSet<String> to JSONObject and then Parse the output 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.

I am using org.json.simple v1.1.

like image 824
Ashraful Islam Avatar asked Jun 22 '16 08:06

Ashraful Islam


People also ask

How do you pass a JSON object into a string in Java?

JSONObject json= (JSONObject) JSONValue. parse(jsonData); JSONObject data = (JSONObject) json. get("data"); After you have parsed the json data, you need to access the data object later get "map" data to json string.

How do you convert a string to a JSON object in Python?

you can turn it into JSON in Python using the json. loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary.

What is JSONObject in android?

Android JSONObject is used for JSON parsing in android apps. In this tutorial we'll discuss and implement a JSONObject in our android application to parse JSON data. JSON stands for JavaScript Object Notation.


Video Answer


1 Answers

I think this is a problem with org.json.simple library.

I have used org.json library, and have to do some minor changes in above code to work:

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"]}
like image 171
Sachin Gupta Avatar answered Sep 30 '22 04:09

Sachin Gupta