How can I cast a JSONObject to a custom Java class?

Geek Stocks picture Geek Stocks · Jun 15, 2014 · Viewed 56k times · Source

In Java (using json-simple) I have successfully parsed a JSON string which was created in JavaScript using JSON.stringify. It looks like this:

{"teq":14567,"ver":1,"rev":1234,"cop":15678}

This string is storing the state of a custom JavaScript object which I now wish to re-constitute as a pure Java class. Its not going well - first foray into Java coming from a C# background. :-p

The object is currently in the form of a org.json.simple.JSONObject since that is what json-simple made from the JSONParser.parse() operation.

How can I cast this JSONObject to my new Java class? (the definition of which is below...)

public class MyCustomJSObject {
    public int teq;
    public int ver;
    public int rev;
    public int cop;
}

Answer

arsen_adzhiametov picture arsen_adzhiametov · Jun 15, 2014

use jackson library

    //create ObjectMapper instance
    ObjectMapper objectMapper = new ObjectMapper();

    //convert json string to object
    Employee emp = objectMapper.readValue(jsonData, Employee.class);