How to convert complex dynamic json to pojo class - java

I have below json
[{
"Maindata": "{\"SubData\":[{\"Name\":\"a\",\"rollnumber\":1,\"ParentName\":c},{\"Name\":\"b\",\"rollnumber\":2,\"ParentName\":d},{\"Name\":\"m\",\"rollnumber\":3,\"ParentName\":n}],\"schooltime\":123213,\"lunchtime\":2321,\"TeacherName\":\"abc\",\"ClassTeacherName\":\"abc\",\"Subjects\":null,\"ClassName\":\"xyz\",\"PrincipleName\":[\"sdffd\"],\"ClassID\":\"21312\",\"books\":\"\",\"classdata\":{\"scienceclass\":\"2hrs\",\"Projects\":\"True\",\"Games\":\"Nothing\"},\"real\":null,\"classuniqueid\":\"21323234234\",\"schoolbelltime\":21323321}"
}]
In above Json we have
MainData - Main data has two main sections
SubData
ClassData
When i tried to view the above Json viewer it displays MainData as main Json and doesnot display sub data json
Now i want to convert above json to Pojo class, in a way say if i give Name of Subdata as "a" it should give me all details of "a". Now Subdata is dynamic, it has three sections now, it can have 100 when new students data are available or it can have only two. How to write a pojo class which reads this and gives data.
I am using gson and Below is my pojo class
public class MyPojo
{
private String Maindata;
public String getMaindata ()
{
return Maindata;
}
public void setMaindata (String Maindata)
{
this.Maindata = Maindata;
}
#Override
public String toString()
{
return "ClassPojo [Maindata = "+Maindata+"]";
}
}

You can use Jackson to convert JSON data to POJOs and POJOs to JSON data.
For complex JSON data like yours, you will need to create ArrayLists of complex types in your corresponding classes.

Paste your valid JSON into this site and select
Target language: Java
Annotation Style: GSON
and download the Zip file, extract it after that you get all POJO classes of your JSON response

Related

Pass multiple JSON data in Request Body of Postman and Get it into Java using undertow API

I want to get multiple JSON data which I am passing into Postman in Body as Json format.
If I am passing single json data like
{
"Name":"Albert",
"PhoneNo":"9846758098",
"Country":"USA"
}
then I am getting the data in java but I want to pass multiple JSON data in postman like this
{
"Count":"2",
"Data":[
{
"Name":"Albert",
"PhoneNo":"9846758098",
"Country":"USA"
},
{
"Name":"Yash",
"PhoneNo":"9847898098",
"Country":"IN"
}
]
}
So for getting this data in java what i need to do
This is what i used to get single JSON data
Now I want to get this data
Your VatData class should be as:
class VatData{
String Count;
List<MyData> Data;
}
and MyData should be as:
class MyData {
String PhoneNo;
String Country;
String Name;
}

How to convert csv to json in apache camel

I able to convert csv into pojo with the help of camel bindy. But I need to convert the string to json easily?
I able to do my splitting the string.But is there any efficient methods to do it?
My pojo Class:-
#CsvRecord(separator = ",",skipFirstLine = true)
public class Sample
{
//some fields
}
Processor Class:-
String samples=exchange.getIn().getBody(String.class);
String[] strings=samples.split("}");
System.out.println(strings[0]);
for(String strings1:strings)
{
String[] strings2=strings1.split("'");
for(int i=0;i<strings2.length;i++)
{
if(i%2==1) {
System.out.println(strings2[i]);
}
}
}
//Is there is efficient method we can do to convert the String to list of json. Assuming csv contains multiple record
Route Builder :-
public class SimpleRouteBuilder extends RouteBuilder {
private final BindyCsvDataFormat bindy=new BindyCsvDataFormat(com.company.model.Sample.class);;
#Override
public void configure() {
from("file:/path/?fileName=CCO_SUMMARY_20190315_165800 copy.csv&noop=true").unmarshal(bindy).process(new MyProcessor()).
to("file:/path/?fileName=akshay.txt");
}
}
Eager to know if there is any efficient method to solve this?
.json()
see camel json data format ie: .json().log("${body}")
In your scenario for example:
from("file:/path/?fileName=CCO_SUMMARY_20190315_165800 copy.csv&noop=true")
.unmarshal(bindy)
.marshal()
.json(JsonLibrary.Jackson).log("${body}")
.to("file:/path/?fileName=akshay.txt");
where json(JsonLibrary.Jackson) forces the use of the jackson library for the conversion.
You can use camel bindy t unmarshal csv to List of POJO
Do mapping if required base on output format
marshal mapped data using Jacson o Gson in Came route.
from("file:/input/path/?noop=true")
.unmarshal(bindy)
.marshal()
.json(JsonLibrary.Jackson).log("${body}")
.to("file:/path/?fileName=test.txt");

Parse JSON without object name in Java

I am trying to parse this JSON which is coming as the response to a REST API call. Can you please help me parsing it as key value pairs?
The object names are not present. There is nesting as well. There seems to be no new line between records.
The aim is to extract this data and load it into a database.
[
{
"cc_emails":["feedback#xyz.com"],
"fwd_emails":[],
"reply_cc_emails":["feedback#xyz.com"],
"fr_escalated":false,
"spam":false,
"email_config_id":6000038087,
"group_id":6000110481,
"priority":1,
"requester_id":6010410791,
"responder_id":6002817857,
"source":1,
"company_id":null,
"status":2,
"subject":"fare",
"to_emails":["feedback#xyz.com"],
"product_id":null,
"id":45043,
"type":null,
"due_by":"2016-03-12T08:58:02Z",
"fr_due_by":"2016-03-08T08:58:02Z",
"is_escalated":false,
"description":"Dear xyze Team,\r\n\r\nWhy r u increased fair again and againasas0mail.gmail.com</a>.<br>\n",
"custom_fields":
{
"category":null,
"issue":null,
"route_id":null,
"phone_number":null,
"department":null,
"booking_id":null
},
"created_at":"2016-03-07T08:58:02Z",
"updated_at":"2016-03-07T08:58:03Z",
// ...... repeat
}
]
The best way to do this would be to use http://www.jsonschema2pojo.org/
Enter your json there
Change source type to JSON
set the correct class name and package.
The resulting pojo can be directly mapped from the json
If you are using resttemplate to hit the api then you can use getForObject to automatically set the pojo from the output.
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#getForObject-java.lang.String-java.lang.Class-java.lang.Object...-
Using gson you can do this quite simply.
Do a class to match the fields in the json something like:
public class Example {
private List<String> cc_emails;
private List<String> fwd_emails;
private List<String> reply_cc_emails;
private Boolean fr_escalated;
private Boolean spam;
private Integer email_config_id;
...
private CustomFields custom_fields;
private String created_at;
private String updated_at;
}
Then you need to do another to map the custom fields
public class CustomFields {
private String category;
...
}
And using json you can parse it like this:
Type type = new TypeToken<Collection<Example>>(){}.getType();
new Gson().fromJson(json,type);
You have to exaplain to Gson it's a list, if it was a single object it would be this:
new Gson().fromJson(json,Example.class);
This is the aproach I usually take, also in the dates java.sql.Timestamp class might also parse it, you would need to try it though.
You can use Gson (https://github.com/google/gson) or Jackson (https://github.com/FasterXML/jackson) and deserialize it to a Map.

How to combine/separate multiple json

i have a json which contains 2 json Objects
{"cityList":[{"id":"2","cityName":"value"}]}
{"subGuildList":[{"id":"340","guildId":"144","subGuildName":"value"}]}
now i want to combine 2 jsons object to one.
What is the integration of the two json object above?
and how can i to separate main json object with java or android?
use Gson or some similar json converter. your Json in incorrect. if you say 1 json contains those 2 object then it's rep should be:
{
"cityList":[{"id":"2","cityName":"value"}],
"subGuildList":[{"id":"340","guildId":"144","subGuildName":"value"}]
}
Your POJO will be:
public class MyObject {
private List<MyCity> cityList;
private List<MyGuid> subGuidList;
}
public class MyCity {
int id;
String cityName;
}

"Dotting" in JSON using Gson on Android

I'm trying to parse a JSON feed using Gson in Android. I know the JSON is valid. I suspect that it is because the format is like this:
"Info":[
{
"Id":"",
"Name":"",
"Description":"",
"Date":""
}
In order to parse this I need to "dot" in. Ex: Info.Name
How can I do this in a serialized DTO?
#SerializedName("Name")
public String name;
#SerializedName("Description")
public String desc;
#SerializedName("Date")
public String date;
I tried to put "Info." in front of each serializedName but that didn't work either. I also know my JSON parsing method works properly, because it's used somewhere else with a different DTO. But in that parsing, I don't have to "dotting" issue.
Can anyone help?
EDIT: I have tried everything you guys posted, and nothing works. The error says:
The JsonDeserializer failed to deserialize json object {"Info":[{".......
SECOND EDIT:
I was able to get rid of the error, but now it returns null. Haha, getting pretty damn frustrated right about now!
I am assuming that the actual JSON you are intaking is valid because the example you provided is not. In your JSON example, you have "Info":[ but there is no outer object containing the "Info" property, which is a must. The valid JSON would be:
{
"Info": [
{
"Id":"",
"Name":"",
"Description":"",
"Date":"",
}
]
}
This is a JSON object that has a property "Info" which has a value that is a list of objects. This list of objects contains one object that has the properties "Id", "Name", "Description", and "Date", all of which have empty-string values.
Here is a quick tutorial on how to use GSON to parse a JSON feed such as the above JSON:
You will need a class to represent the items in the list:
public class InfoItem {
public String Id;
public String Name;
public String Description;
public String Date;
public InfoItem() {}
}
And one to represent the list of Items:
public class InfoItemList extends LinkedList<InfoItem> {
public InfoItemList() { super() };
}
This added complexity is because GSON cannot otherwise get the type of a generic collection from the class data.
And one to represent the overall JSON message:
public class InfoMessage {
public InfoItemList Info;
public InfoMessage() {};
}
And then just:
gson.fromJson(jsonString, InfoMessage.getClass());
If just de-serializing a collection:
Type listType = new TypeToken<List<InfoItem>>() {}.getType();
gson.fromJson(jsonString2, listType);
The Info object is a list because of the []. You have to use the following code to deserialze it:
EDIT:
public class Info {
// as in your question
public String name;
...
}
public class Data {
#SerializedName("Info")
public List<Info> info;
}
Then just use the data class to deserialize your json.

Categories