Converting a specific JSON to java object format? [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 9 years ago.
Iam new to java script and JSON, please help me in solving my problem. Below is the structure of my JSON in JavaScript
{
"name": "sample",
"def": [
{
"setId": 1,
"setDef": [
{
"name": "ABC",
"type": "STRING"
},
{
"name": "XYZ",
"type": "STRING"
}
]
},
{
"setId": 2,
"setDef": [
{
"name": "abc",
"type": "STRING"
},
{
"name": "xyz",
"type": "STRING"
}
]
}
]
}
in the backend, what should be the synatx of java method to receive this data
public void getJsonData(****){
}
How to parse this JSON data in java and what should be the syntax of method parameter ?
update 1: Edited the json format to make it valid

First create a class that will map your json object and give a name something like "DataObject". Then use the gson library and do the following:
String s = "";
DataObject obj = gson.fromJson(s, DataObject.class);

Your JSON is invalid, but assuming you fix that then you are looking for a library in Java which will serialize an annotated Java class to JSON, or deserialize JSON data to an annotated Java class.
There is a whole list of suitable libraries here:
http://json.org/java/

Related

Jackson JSON Deserialization - How to assign object members based on JSON values?

I have some ugly JSON that I need to deserialize which looks like the following:
"ContainerValues": [
{
"ParentAttribute": "QuantityContained",
"RowList": [
{
"Values": [
{
"Name": "Code",
"ValuesByLocale": {
"en-US": "GRM"
},
},
{
"Name": "Value",
"ValuesByLocale": {
"en-US": "4.0"
},
}
],
}
],
}
],
This is just a sample of the JSON I have. All I need to do is to get this into a POJO which looks like something like the following:
Class POJO{
String grmValue; // This is the "Value" for the GRM "Code" above, i.e. "4.0"
...
}
Any idea how I might be able to assign the value of grmValue based on the JSON above using Jackson? I'm starting to think I'll need to write a custom deserializer.
First You have to deserialize to class similar to your JSON, then transform to your POJO format :)

How to select fields in different levels of a jsonfile with jsonPath?

I want to convert jsonobjcts into csv files. Wy (working) attempt so far is to load the json file as a JSONObject (from the googlecode.josn-simple library), then converting them with jsonPath into a string array which is then used to build the csv rows. However I am facing a problem with jsonPath. From the given example json...
{
"issues": [
{
"key": "abc",
"fields": {
"issuetype": {
"name": "Bug",
"id": "1",
"subtask": false
},
"priority": {
"name": "Major",
"id": "3"
},
"created": "2020-5-11",
"status": {
"name": "OPEN"
}
}
},
{
"key": "def",
"fields": {
"issuetype": {
"name": "Info",
"id": "5",
"subtask": false
},
"priority": {
"name": "Minor",
"id": "2"
},
"created": "2020-5-8",
"status": {
"name": "DONE"
}
}
}
]}
I want to select the following:
[
"abc",
"Bug",
"Major",
"2020-5-11",
"OPEN",
"def",
"Info",
"Minor",
"2020-5-8",
"DONE"
]
The csv should look like that:
abc,Bug,Major,2020-5-11,OPEN
def,Info,Minor,2020-5-8,DONE
I tried $.issues.[*].[key,fields] and I get
"abc",
{
"issuetype": {
"name": "Bug",
"id": "1",
"subtask": false
},
"priority": {
"name": "Major",
"id": "3"
},
"created": "2020-5-11",
"status": {
"name": "OPEN"
}
},
"def",
{
"issuetype": {
"name": "Info",
"id": "5",
"subtask": false
},
"priority": {
"name": "Minor",
"id": "2"
},
"created": "2020-5-8",
"status": {
"name": "DONE"
}
}
]
But when I want to select e.g. only "created" $.issues.[*].[key,fields.[created]
[
"2020-5-11",
"2020-5-8"
]
This is the result.
But I just do not get how to select "key" and e.g. "name" in the field issuetype.
How do I do that with jsonPath or is there a better way to filter a jsonfile and then convert it into a csv?
I recommend what I believe is a better way - which is to create a set of Java classes which represent the structure of your JSON data. When you read the JSON into these classes, you can manipulate the data using standard Java.
I also recommend a different JSON parser - in this case Jackson, but there are others. Why? Mainly, familiarity - see later on for more notes on that.
Starting with the end result: Assuming I have a class called Container which contains all the issues listed in the JSON file, I can then populate it with the following:
//import com.fasterxml.jackson.databind.ObjectMapper;
String jsonString = "{...}" // your JSON data as a string, for this demo.
ObjectMapper objectMapper = new ObjectMapper();
Container container = objectMapper.readValue(jsonString, Container.class);
Now I can print out all the issues in the CSV format you want as follows:
container.getIssues().forEach((issue) -> {
printCsvRow(issue);
});
Here, the printCsvRow() method looks like this:
private void printCsvRow(Issue issue) {
String key = issue.getKey();
Fields fields = issue.getFields();
String type = fields.getIssuetype().getName();
String priority = fields.getPriority().getName();
String created = fields.getCreated();
String status = fields.getStatus().getName();
System.out.println(String.join(",", key, type, priority, created, status));
}
In reality, I would use a CSV library to ensure records are formatted correctly - the above is just for illustration, to show how the JSON data can be accessed.
The following is printed:
abc,Bug,Major,2020-5-11,OPEN
def,Info,Minor,2020-5-8,DONE
And to filter only OPEN records, I can do something like this:
container.getIssues()
.stream()
.filter(issue -> issue.getFields().getStatus().getName().equals("OPEN"))
.forEach((issue) -> {
printCsvRow(issue);
});
The following is printed:
abc,Bug,Major,2020-5-11,OPEN
To enable Jackson, I use Maven with the following dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
In case you don't use Maven, this gives me 3 JARs: jackson-databind, jackson-annotations, and jackson-core.
To create the nested Java classes I need (to mirror the structure of the JSON), I use a tool which generates them for me using your sample JSON.
In my case, I used this tool, but there are others.
I chose "Container" as the name of the root Java class; a source type of JSON; and selected Jackson 2.x annotations. I also requested getters and setters.
I added the generated classes (Fields, Issue, Issuetype, Priority, Status, and Container) to my project.
WARNING: The completeness of these Java classes is only as good as the sample JSON. But you can, of course, enhance these classes to more accurately reflect the actual JSON you need to handle.
The Jackson ObjectMapper takes care of loading the JSON into the class structure.
I chose to use Jackson instead of JsonPath, simply because of familiarity. JsonPath appears to have very similar object mapping capabilities - but I have never used those features of JsonPath.
Final note: You can use xpath style predicates in JsonPath to access individual data items and groups of items - as you describe in your question. But (in my experience) it is almost always worth the extra effort to create Java classes, if you want to process all your data in more flexible ways - especially if that involves transforming the JSON input into different output structures.

How to create an object class that can converted to json like this in java? [duplicate]

This question already has answers here:
Is there a way to create the bean class from a json response
(6 answers)
Closed 3 years ago.
This is the JSON request that I need to pass to other API, My problem is I dont know how to create an object that can have other object inside.
What is the best approach for this, I'll be using ObjectMapper to convert the object into json like this.
{
"request": {
"head": {
"version": "1.0.0",
"function": "sample.function",
"clientId": "clientId",
"clientSecret": "clientSecret",
"reqTime": "2001-07-04T12:08:56+05:30",
"reqMsgId": "reqMessageID",
"reserve": ""
},
"body": {
"occurTime": "2018-03-04T12:08:56+08:00",
"bizScene": "SAMPLE_BIZ",
"envInfo": {
"tokenId": "jkahsdhsjakdhkjsajdsahdkjsakdhsa===",
"clientIp": "127.0.0.1",
"appVersion": "v0.1.0",
"terminalType": "NOP"
},
"extendInfo": {
"PSID":"87943297427",
"PSID_CreatedDate":"2018-01-04T12:08:56+08:00",
"mobtelLinkingDate" : "2018-03-04T12:08:56+08:00",
"mobtelUnlinkingDate" : "2018-04-04T12:08:56+08:00",
"activeLinkedMobtel" : "123756"
},
"accountInfo": {
"userMobile": "123756"
},
"operationInfoDTO" : {
"operationOrigin": "TWEETER",
},
"operationType": "SAMPLE",
"operationResult": "FALSE",
}
},
"signature": "signature string"
}
I gave a name to the root Object a used this website to generate boilerplate bean object
"rootObj":{
"request": {
"head": {
"version": "1.0.0",
"function": "sample.function",
"clientId": "clientId",
"clientSecret": "clientSecret",
"reqTime": "2001-07-04T12:08:56+05:30",
"reqMsgId": "reqMessageID",
"reserve": ""
},
"body": {
"occurTime": "2018-03-04T12:08:56+08:00",
"bizScene": "SAMPLE_BIZ",
"envInfo": {
"tokenId": "jkahsdhsjakdhkjsajdsahdkjsakdhsa===",
"clientIp": "127.0.0.1",
"appVersion": "v0.1.0",
"terminalType": "NOP"
},
"extendInfo": {
"PSID":"87943297427",
"PSID_CreatedDate":"2018-01-04T12:08:56+08:00",
"mobtelLinkingDate" : "2018-03-04T12:08:56+08:00",
"mobtelUnlinkingDate" : "2018-04-04T12:08:56+08:00",
"activeLinkedMobtel" : "123756"
},
"accountInfo": {
"userMobile": "123756"
},
"operationInfoDTO" : {
"operationOrigin": "TWEETER",
},
"operationType": "SAMPLE",
"operationResult": "FALSE",
}
},
"signature": "signature string"
}
There are some minor syntax errors in your JSON example in line 33 and 36.
JSON doesn't like comma after the last element of a list or dictionary.
If you remove those and use this JSON as input for http://www.jsonschema2pojo.org/ you'll get corresponding Java classes.

How to get the nested property of a JSON response using Jackson library? [duplicate]

This question already has answers here:
How to get a value from a JSON string using jackson library?
(3 answers)
Closed 3 years ago.
I have the following JSON schema from the response of an API which can either be :
{
"meta": {
"someData": " "
},
"A": [
{
"code": 123,
"id": "string",
"data": {}
},
{
"code": 123,
"id": "string",
"data": {}
}
]
}
OR
{
"meta": {
"someData": " "
},
"B": [
{
"code": 123,
"id": "string",
"data": {}
},
{
"code": 123,
"id": "string",
"data": {}
}
]
}
How do I get obtain just the date from the list or either property A or property B ?
I expect output to be something like:
A[0].data = {}
A[1].data = {}
OR
B[0].data = {}
B[1].data = {}
And
I want to store the data property, which is an object with variable number of sub properties in a map.
You should be able to use jackson's object mapper. You should create a class or interface to define your json object as well. The A or B may be an issue. You might be able to create a class/interface for each.
final ObjectMapper objectMapper = new ObjectMapper();
final CallbackRequest callbackRequest = objectMapper.readValue(json, CallbackRequest.class);
Also, here is an example: https://github.com/NikhilShah1647/jackson-example/blob/master/src/main/java/com/journaldev/jackson/json/JacksonObjectMapperExample.java
And here is an example of deserializing a json object with possible multiple types: Jackson deserialization of type with different objects

How to convert nested Json in string into Json object in java

I am looking for some Java library, which can convert below give String into Json object.
Input: String reading from file.
{ "product": "{\"sku\":\"rtwre-rtwe\",\"price\":\"50.90\",\"currency_code\":\"SGD\",\"quantity\":1}", "is_organic": "0", "can_claim": "0", "t": "r", "device": "Phone", "amount_transactions": "0" }
Expected output: In some generic Java Json object.
{
"product": {
"sku": "rtwre-rtwe",
"price": "50.90",
"currency_code": "SGD",
"quantity": 1
},
"is_organic": "0",
"can_claim": "0",
"t": "r",
"device": "Phone",
"amount_transactions": "0"
}
Imp points: This is sample code, I have more dynamic json and don't have any Java object corresponding to my json. I can have string json in any key. It's not specific to particular key. I am looking for more generic code.
Here my goal if I read value of key "product" it should return Json instead of String. I want to read $.product.price using JsonPath library. http://jsonpath.com/
Edit1: I don't have much experience with Gson, Jackson and JsonObject libraries, but I tried whatever I could do. If you had handled the same scenario, please help me out.
To resolve it you can use :
JSONObject jsonObj = new JSONObject(myStringValue);
String myJsonStructureAsString = jsonObj.toString();
Where JSONObject is org.json.JSONObject form lib json-org.v2017.05.16.jar

Categories