简体   繁体   中英

Java : Json String with ANSI escape code to Object

I have the below String in Java,

String ansiStr = "{\"traceback\":[\"\\u001b[1;36m  File \\u001b[1;32m\\\"MyFile\\\"\\u001b[1;36m, line \\u001b[1;32m1\\u001b[0m\\n\\u001b[1;33m    codedata\\u001b[0m\\n\\u001b[1;37m                         ^\\u001b[0m\\n\\u001b[1;31mSyntax\\u001b[0m\\u001b[1;31m:\\u001b[0m EOF\\n\"],\"ename\":\"Error\",\"evalue\":\"UnExpected\"}";

The String is a reply from IPython kernel and looks like in JSon format and i tried the below code to parse it as an object,

ArrayList list = gson.fromJson(jsonString, ArrayList.class);

I get the following exception,

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $

How can i convert this String in to a JSon object ? What should be the Class/Type ? I am stuck as it has ANSI color codes to it with "[" symbol.

Try this

try {
        JSONObject object=new JSONObject(ansiStr);
        TrackBook track = new Gson().fromJson(object.toString(),TrackBook.class);
        List<String> trackList=track.getTraceback();
    } catch (JSONException e) {
        e.printStackTrace();
    }

TrackBook.java

public class TrackBook {
@SerializedName("traceback")
@Expose
private List<String> traceback = null;
@SerializedName("ename")
@Expose
private String ename;
@SerializedName("evalue")
@Expose
private String evalue;

public List<String> getTraceback() {
    return traceback;
}

public void setTraceback(List<String> traceback) {
    this.traceback = traceback;
}

public String getEname() {
    return ename;
}

public void setEname(String ename) {
    this.ename = ename;
}

public String getEvalue() {
    return evalue;
}

public void setEvalue(String evalue) {
    this.evalue = evalue;
}
}

The problem is that you are trying to read your JSON as an ArrayList , but it's not an array - it's an object:

{
    "traceback": [...], // this is actually an array
    "ename": "Error",
    "evalue": "UnExpected"
}

And the error message you receive hints at it: Expected BEGIN_ARRAY but was BEGIN_OBJECT .

So all you need to do is to read it as a Map :

Map map = gson.fromJson(ansiStr, Map.class);

Gson will automatically detect that traceback is an array and create a List for it. You can test it like this:

System.out.println(((List) map.get("traceback")).get(0));

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