How one can represent the JSON Object in clean POJO? - java

I'm very new to Java. I'm just parsing a string and getting the Json Response like this:
{
"customer_id": "user",
"merchantId": "xxxx",
"cards":
[
{
"card_token": "715fc10a-e7b3-48a1-b6e7-09e71ac050f8",
"card_number": "11111111",
"card_isin": "23232",
"card_exp_year": "2013",
"card_exp_month": "12"
}
]
}
For some reason I wish I could be able to represent this in a POJO. Note that the cards field can consist of more than 1 field.
I'm new to Java. I don't want the code for doing it, but I want to know what is the best way to represent these structure in POJO.

You can use GSON that can easily convert json to java object (generic) and vice versa which further you can use for your POJO.

- Manual parsing of JSON to object will be a pain.
- Its better to go with Jackson, which i use.
- Or you can also choose GSON (created by google for its internal use initially).
See this link for implementation example:
http://www.mkyong.com/java/json-simple-example-read-and-write-json/

The two dominate JSON processors for Java are GSON (as #Abu points out in his answer) and Jackson. These libraries will help you map a Java POJO to a JSON object, and vice-versa.
Here is a comparison on SO.

You can also use Jackson JSON. It's a bit faster and it works great with the Java API for RESTful Services (JAX-RS), the Java standarization for REST api's.
Here's a better comparison between the two: Jackson Vs. Gson
To read an object from String, checkout the ObjectMapper class.

Related

Best way to generate JSON dynamically [duplicate]

This question already has answers here:
Parsing JSON string in Java
(7 answers)
Closed 2 years ago.
I am testing REST APIs. Each API consumers the different type of JSON payload.
I don't want to fill all input manually. So, I want to generate JSON dynamically (e.g. read values from a text file and fill in JSON structure) and then pass the generated JSON as Request Body in API.
What is the best way to do so?
Any recommendations for tools or a plugin?
P.S. The JSON structure in Nested and very complex.
This is the same I was having some weeks ago.
What I did, might be helpful to you too:
I used private Map<String, Object> data;
in my DTO where I wanted to have Dynamic JSON.
like if my JSON is:
{
"key":{
"key1":["1","2","3"]
},
"key2":{
}
}
then this JSON will be saved as a Map which you can use to parse your JSON data.
and for parsing try using org.json
For example:
JSONObject jsonObject = new JSONObject(mapFromDTO);
And now you have full access to JSON, which was your core issue.
The answer lies in defining the contract. Decide first on what are the maximum possible values in your JSON.
Example, for start you can decide on following contact:
{
"id": 1,
"name": "Username",
"age": 30,
"phone": 900000000
}
Once contract is finalised, design a POJO. This POJO can be very complex data structure which can have fields or may be list of fields (objects). This is totally dependent on your business.
You can then write a java service which can generate this POJO based on some complex business logic.
Once this POJO is populated use 3rd party library like jackson to convert it to JSON.
Further reading:
https://www.tutorialspoint.com/how-to-convert-java-object-to-json-using-jackson-library

How to convert JsonForm to Json?

I would like to extract only the data present in a Json to JsonForm using Java.
Which framework can I use to this operation?
I've found the answer. Don't let the ugly aspect of JsonForm deceive you. I don't know if this apply for all cases, but I just had to extract the Json object that contains only the data. This can be done using any common Json parser, as like as Gson.

How can I easily serialize Java graph to/from JSON?

I am struggling to find a library that will serialise a simple graph of Java objects to/from JSON (no need for circular refs or anything). I don't want to have Java class names in the output but including an extra "#type": "foo" property is fine. It must work with untyped collections and maps. I expect to have to do something like mapper.registerType(MyClass.class, "foo") to specify the type mappings but the library must take it from there. Anyone know of such a thing?
Jackson should be able to handle what it is that you are trying to do. Check out the examples from this link, most specifically #4 for polymorphic type deserialization
Jackson
Polymorphic Type Handling
Examples
Take a look at Genson it provides full databinding support, with polymorphic and untyped objects and has many other features.
// this defines aliases for classes, if you don't care of class names being
// serialized then just enabled type ser/deser using builder.setWithClassMetadata(true)
Genson genson = new Genson.Builder()
.addAlias("person", Person.class)
.addAlias("other", Some.class)
.create();
// serialize using with type information
String json = genson.serialize(object);
// deserializing to an unkown type based on the type information in the json string
genson.deserialize(json, Object.class);
Do you search something like this?
http://code.google.com/p/json-io/
json-io consists of two main classes, a reader (JsonReader) and a
writer (JsonWriter). There is a 3rd rigorous test class
(TestJsonReaderWriter). json-io eliminates the need for using
ObjectInputStream / ObjectOutputStream to serialize Java and instead
uses the JSON format.
...
Usage
json-io can be used directly on JSON Strings or with Java's Streams.

What is the fastest way to deserialize JSON in java

I'm wondering what is the fastest way to parse json in JAVA ?
Getting a default object graph using the library built in Array, and Object objects
Getting a custom object graph using your own java bean
Thanks
Well, The newest and wickedly Fastest one is Boon Json. I used it in my project and got an improvement of 20X. I actually got scared and double checked to see if Library is functionally correct. Thankfully, it is :) :)
Boon has built in methods to serialize and de-serialize from/to Java Array/Maps and Custom Beans.
More Here : https://github.com/RichardHightower/boon
Mapping parsed JSON to Java bean involves additional steps, so using the raw interface (e.g. the streaming API of Jackson) will be faster. This way, you can also read until have what you need and stop parsing.
In response to #sikorski
From Jackson Wiki:
Data binding is built using Streaming API as the underlying JSON
reading/writing system: as such it has high-performance [...], but has
some additional overhead compared to pure streaming/incremental
processing
This is pretty much inevitable. If you are writing a generic Jackson parser, you obviously can't use custom types in it. Therefore it follows that you'll have to construct the custom type after you read the JSON with the generic parser, and hence the generic parser will be faster. It's worth noting though that such overhead is very small and almost never something you need to optimize away.
You can use json-simple its a high performance library and its very easy to use :
JSONParser parser=new JSONParser();
System.out.println("=======decode=======");
String s="[0,{\"1\":{\"2\":{\"3\":{\"4\":[5,{\"6\":7}]}}}}]";
Object obj=parser.parse(s);
JSONArray array=(JSONArray)obj;
System.out.println("======the 2nd element of array======");
System.out.println(array.get(1));
System.out.println();
JSONObject obj2=(JSONObject)array.get(1);
System.out.println("======field \"1\"==========");
System.out.println(obj2.get("1"));
s="{}";
obj=parser.parse(s);
System.out.println(obj);
s="[5,]";
obj=parser.parse(s);
System.out.println(obj);
s="[5,,2]";
obj=parser.parse(s);
System.out.println(obj);

How to create a JSON document using Java?

I want to read data from the database, convert it to docs (JSON) using Java.
Thanks
GSON is a Java library from Google to convert Java objects to JSON. You can simply pass a Java object to the library function and it will return a JSON string.
Download: http://code.google.com/p/google-gson/
Example: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
I have used the library from http://www.json.org, but the whole thing seems to be tedious to me. GSON is simple to use IMHO.
I would use JSONObject class:
http://www.json.org/javadoc/org/json/JSONObject.html
or you can build the string.

Categories