1

I have a JSON stored in a string.

String data = "{code: '0', distCode: '123'}";

I need to get the values of code, distCode. But when I try to parse it as below

JSONParser parser = new JSONParser();
JSONObject Details = (JSONObject) parser.parse(data);

Unexpected character (c) at position 2 exception is thrown.

I am sure it is because of unquoted keys in the string. How to parse the string into an JSON object using org.json.simple library?

2
  • Make it look like this "{\"code\":\"'0\", \"distCode\": \"123\"}" Commented Apr 18, 2020 at 7:43
  • I don't think you can; it's not valid JSON. You might be able to do something tricky like using an embedded JavaScript engine to evaluate it as a JavaScript object. Commented Apr 18, 2020 at 8:20

1 Answer 1

0

Could not find way to achieve it using org.json.simple library. Finally done it using jackson libraries.

    String data = "{code: '0', distCode: '123'}";
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);                               
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    Map<String, String> Shop_Details = mapper.readValue(data), Map.class);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.