简体   繁体   中英

Is there a JSONParser method to parse the following string structure in Java?

My JSON String output is as below.
{'errorcode': '0', 'errormessage': "'success'", 'parsedoutput': [{'columnname': 'salary', 'columnalias': 'sal', 'tablename': 'employee', 'expression': 'salary', 'schemaname': 'prod', 'tablealias': 'e'}]}

And I want to parse this string and get the values. Gone thru many links here but found none working to my requirement. So posted as new question, hope no issues.

Error I'm getting when I run my code:

Unexpected character (') at position 1.
    at org.json.simple.parser.Yylex.yylex(Unknown Source)
    at org.json.simple.parser.JSONParser.nextToken(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at org.json.simple.parser.JSONParser.parse(Unknown Source)
    at com.jsontostring.JSONToStringTest.main(JSONToStringTest.java:18) 

My Java Code which I used to parse the json string..

public class JSONToStringTest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String jsonString = "{'errorcode': '0', 'errormessage': \"'success'\", 'parsedoutput': [{'columnname': 'salary', 'columnalias': 'sal', 'tablename': 'employee', 'expression': 'salary', 'schemaname': 'prod', 'tablealias': 'e'}]}";

    try {
        JSONParser parser = new JSONParser();
        JSONObject json = (JSONObject)parser.parse(jsonString);

        System.out.println(json.get("errorcode"));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

As others commented under original post, your JSON string is not valid. Therefore, one way is to parse the given string directly and the other way is to make the invalid JSON string be valid, then parse it by any popular JSON libraries.

Method 1
If you are using JAVA 8, you can easily retrieve the value of errorcode with Stream as follows:

String errorCode = Arrays.asList(jsonStr.split(","))
    .stream()
    .filter(e -> e.contains("errorcode"))
    .findFirst()
    .get()
    .split(":")[1]
    .trim()
    .replace("'", "");
    System.out.println(errorCode);

Method 2

JSONObject jsonObj = new JSONObject(jsonStr.replace("'", "\"").replace("\"\"", "\""));
String errorCode = jsonObj.get("errorcode").toString();
System.out.println(errorCode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM