Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
}
like image 298
Geek Stocks Avatar asked Jun 15 '14 15:06

Geek Stocks


People also ask

How do you assign a JSON object to a class in Java?

parse() method, it all works out like so: //JSONParser parser = new JSONParser(); // DON'T USE THIS Object obj = JSONValue. parse("A JSON string - array of objects: [{},{}] - goes here"); JSONArray arrFilings = (JSONArray)obj; System. out.

How do you parse a JSON object in Java?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

How do you pass a JSON object into a string in Java?

Stringify a JavaScript Object stringify() to convert it into a string. const myJSON = JSON. stringify(obj); The result will be a string following the JSON notation.

Can we convert object to JSONObject in Java?

The ObjectMapper class of the Jackson API provides methods to convert the Java object to JSON format or object. The ObjectMapper class writeValueAsString() method takes the JSON object as a parameter and returns its respective JSON string.


3 Answers

Add dependency from https://github.com/google/gson and use it like

Gson gson= new Gson();
CustomPOJOClass obj = gson.fromJson(jsonObject.toString(),CustomPOJOClass.class);
like image 184
Milon Avatar answered Oct 05 '22 18:10

Milon


use jackson library

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

    //convert json string to object
    Employee emp = objectMapper.readValue(jsonData, Employee.class); 
like image 36
arsen_adzhiametov Avatar answered Oct 05 '22 19:10

arsen_adzhiametov


There are lot of libraries that does this. This is my suggestion. Here you can find the library

import com.google.gson.Gson; 

and then do,

Gson gson = new Gson();  
Student student = gson.fromJson(jsonStringGoesHere, Student.class);  

Maven Dependency

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.4</version>
    </dependency>
like image 8
diyoda_ Avatar answered Oct 05 '22 17:10

diyoda_