Best way to generate JSON dynamically [duplicate] - java

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

Related

Best practice to create POJO / DTO for sending deep nested JSON

When developing our API in spring boot that interacts with a third party API, I have to create a DTO to populate and send to a third party. Thing is, the required JSON has a ton of nested objects. For example:
{
"profile": {
"firstName": "firstname",
"credentials": {
"password" : {
"hook": {
"type": "default"
}
}
}
}
}
So, what is simple to express in a JSON object is not simple to express in POJO/DTO classes, due to the high number of nested objects.
Should I create public or anonymous classes for all the nested properties? Or is there a better way to do this?
For example using anonymous, I can keep everything in one java file by not making the subobjects public. What are your techniques for this?
known problem... what I used often:
wrap (hide) third party api in a module
create custom pojo(s) containing only values needed from your domain logic
use only this pojo(s) to interact between your domain/third party module
create module private/inner classes mapping the third party api model as pojos
or consider using nested maps instead with custom jackson de/serializers
map domain pojo to api pojos
or, a bit hacky, if you only need to change same values
store json request payload as a template with placeholders
use e.g. regex to replace before send
You can do what you suggested or simply de-serialize it into Map<String, Object> Using map makes it easy but you won't have content validation and modifying the content (if you need it becomes complex)

Jackson generate JsonSchema from string JSON object

I have a following object:
String jsonObject = "{\"cat\": \"nice cat\"}"
From this I want to get com.fasterxml.jackson.module.jsonSchema.JsonSchema class object.
But I can't find a way how to achieve this without having a Java class beforehand.
Any help would be much appreciated.
The goal I am trying to achieve is to generate Kafka Connect Schema from a JSON string. For this I need first to get JsonSchema from a JSON string.
After more research and more thought put into it, such method does not exist for obvious reasons. Imagine for example a valid JSON:
{
"a": [],
"b": null
}
Then there is no way to tell what are types of a or b.
Therefore I need to be more clever here in what I am trying to achieve.

Gson streaming API with different types of objects according to value of JSON field

I'm trying to parse the Wikidata JSON dump using the Gson streaming API, since the file is around 70GB of json. The overall structure of the file is as follows:
[
{"type":"item",... other fields ...},
{"type":"property",... other fields ...},
.....
]
It is an array of objects in which each object can be of type item or property and I would like to instantiate a different class (namely I have a corresponding Item and Property class in my Java code) according to the object that I encounter.
Basically, I'd like to look at the type field and then parse the following JSON accordingly. Since the JsonReader doesn't seem to provide a getNextJsonObject() or similar function, is there a way to do this besides preprocessing the whole file and splitting the entries into two separate ones? The file is so big that I'd like to avoid the extra preprocessing step when I could do everything on the fly.
I actually found a very easy solution after a bit of thinking. The Gson API provides the method:
Gson.fromJson(JsonReader reader, Class class)
This will read the next object from the reader and deserialize to the class you pass as parameter. Since in my case I don't know which class to serialize to I can do the following:
JsonObject asd = gson.fromJson(reader, JsonObject.class);
if (asd.get("type").getAsString().equals("item")) {
// Instantiate item
} else {
// Instantiate property
}

Using custom inputSplit and/or recordReader classes for reading JSON

In my hadoop class they are wanting us to learn how to write/configure custom input format classes to handle data that isn't simply one record per line (like TextInputFormat).
The data is JSON data from the Twitter API, so it is basically a list of small JSON objects each representing tweets.
[
{
"text":"tweet string",
...more...
},
{
....
},
]
The lab spec suggests focusing on writing a custom recordReader class that manually parses JSON in the given InputSplit, using something like a stack to keep track of opening/closing braces. Frankly this seems idiotic to me, I should not have to reinvent the wheel of parsing JSON... that's the advantage to using a standard data format.
Instead I was hoping to come up with a better solution using an existing JSON parser like json-simple. It seems I should be able to make a custom InputSplit class that splits the list of JSON objects into smaller sublists, and then the custom recordReader would also use the JSON parser to get each JSON object individually.
Is this a proper approach? Should I be customizing an InputSplit? Is there a better way to make a large JSON text consumable by a Hadoop MapReduce job?

How one can represent the JSON Object in clean POJO?

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.

Categories