简体   繁体   中英

Converting malformed json array string to Java object

I have a malformed json array string which I get from an API call as follows:

[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]

There is a double quote before open square bracket in the value of Response Msg property. Is there a way to convert this into Java object ?

What I have tried so far: I have used Jackson to parse it as follows but it gives error

ObjectMapper mapper = new ObjectMapper();
            mapper.setPropertyNamingStrategy(new ResponseNameStrategy());
            Response[] response = mapper.readValue(strOutput1, Response[].class);
Error: Can not deserialize instance of java.util.ArrayList out of VALUE_STRING token

I have also tried using Gson to parse it but it also gives error

Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                    .create();
            Response[] response = gson.fromJson(strOutput1, Response[].class);
Error: Expected BEGIN_ARRAY but was STRING at line 1 column 35 path $[0].ResponseMsg

I have gone through the following links on StackOverflow but none of them has addressed my issue:

How to Convert String Array JSON in a Java Object

Convert a JSON string to object in Java ME?

JSON Array to Java objects

Convert json String to array of Objects

converting 'malformed' java json object to javascript

I think the answer is in the comments, you appear to be trying to solve the issue on the wrong place.

You are receiving json which you wish to parse into java objects, unfortunately the json is malformed so will not parse.

As a general rule you should never be trying to solve the symptom, but should look for the root cause and fix that, it may sound trivial but fixing symptoms leads to messy, unpredictable, and unmaintainable systems.

So the answer is fix the json where it is being broken. If this is something or of your control, while you wait for the fix, you could put a hack in to fix the json before you parse it.

This way you won't compromise your parsing, and only have a small piece of string replacement to remove when the third party has fixed the issue. But do not go live with the hack, it should only be used during development.

As i mentioned in the comment, you should prepare your service response in order to parse it.

I implemented an example:

public class JsonTest {
    public static void main(String args[]) throws JsonProcessingException, IOException{
        String rawJson = 
                "[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Processed successfully\"}]\"}]";
        String goodJson = "{"+rawJson.split("[{{.}]")[2]+"}";
        ObjectMapper mapper = new ObjectMapper();
        final ObjectNode node = mapper.readValue(goodJson, ObjectNode.class);
        System.out.println("Pretty Print: " + mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node));

        System.out.println("Just code: " + node.get("Code"));   
    }

}

Which returns:

产量

This is how I finally solved my issue:

String inputJsonStr = "[{\"ResponseCode\":1,\"ResponseMsg\":\"[{\"Code\":\"CA2305181\",\"Message\":\"Claim has been added successfully.\"}"
                + "]\"}]";
int indexOfRes = inputJsonStr.indexOf("ResponseMsg");

        if(inputJsonStr.substring(indexOfRes+13,indexOfRes+14).equals("\""))
        {
            inputJsonStr = inputJsonStr.substring(0,indexOfRes+13) + inputJsonStr.substring(indexOfRes+14);
        }
        int indexOfFirstClosingSquare = inputJsonStr.indexOf("]");
        if(inputJsonStr.substring(indexOfFirstClosingSquare+1, indexOfFirstClosingSquare+2).equals("\"")) {
            inputJsonStr = inputJsonStr.substring(0, indexOfFirstClosingSquare+1)+inputJsonStr.substring(indexOfFirstClosingSquare+2);
        }

Now inputJsonStr contains a valid json array which can be parsed into Java custom object array easily with gson as given in this SO link:

Convert json String to array of Objects

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