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;
}
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.
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.
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.
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.
Add dependency from https://github.com/google/gson and use it like
Gson gson= new Gson();
CustomPOJOClass obj = gson.fromJson(jsonObject.toString(),CustomPOJOClass.class);
use jackson library
//create ObjectMapper instance
ObjectMapper objectMapper = new ObjectMapper();
//convert json string to object
Employee emp = objectMapper.readValue(jsonData, Employee.class);
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With