I need to convert below JSON to Java classes
Here is the JSON
{
"browserName": "chrome",
"env": "test",
"envUrls1": {
"qatesta": {
"fName": "test",
"lName": "test",
"email": "3242342",
"password": "passTestaa"
},
"qatestb": {
"fName": "test",
"lName": "test",
"email": "3242342",
"password": "passTestaa"
},
"qatestc": {
"fName": "test",
"lName": "test",
"email": "3242342",
"password": "passTestaa"
}
}
}
Using above JSON body I able to creates below classes.
1.
public class JsonConfMainObj {
private String browserName;
private String env;
private EnvUrls1 envUrls1;
}
2.
public class EnvUrls1 {
private Qatesta qatesta;
private Qatestb qatestb;
private Qatestc qatestc;
}
3. In each above 'Qatesta', 'Qatestb' and 'Qatestc' Java Classes Contains the below-repeated values
public class Qatestx{
private String fname;
private String lname;
private String email;
private String password;
}
But I need to avoid repeating the above attributes in each class and move them to common Class and map to 'Qatesta', 'Qatestb', and 'Qatestc'.
like below
public class Qatesta{
private Common com;
}
public class Qatestb{
private Common com;
}
public class Qatestc{
private Common com;
}
public class Common{
private String fname;
private String lname;
private String email;
private String password;
}
Is there a way to do this?
You Can use only One class and give the different variable assigned for that class for eg in EnvUrls1 give class Qatest assigned 3 different values
1.
public class JsonConfMainObj {
private String browserName;
private String env;
private EnvUrls1 envUrls1;
}
2.
public class EnvUrls1 {
private Qatest qatesta;
private Qatest qatestb;
private Qatest qatestc;
}
public class Qatest{
private String fname;
private String lname;
private String email;
private String password;
}
Related
Unable to map json string with java object, getting error JSON parse error: Can not construct instance of com.test.CPInput$Evc$Uni
error:
{
"timestamp": 1502270576300,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "**JSON parse error: Can not construct instance of com.test.CPInput$Evc$Uni: can only instantiate non-static inner class by using default, no-argument constructor; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of com.test.CPInput$Evc$Uni: can only instantiate non-static inner class by using default, no-argument constructor at [Source: java.io.PushbackInputStream#edc246; line: 20, column: 9] (through reference chain: com.test.CPInput["evc"]->com.test.CPInput$Evc["uni"]->java.util.ArrayList[0]**)",
"path": "/demo/addCustomer"
}
json
{
"customerId": "abcdef",
"customerSegment": {
"customerType": "customer type",
"customerSubtype": "subtype",
"industry": "industry",
"subIndustry": "subindustry",
"specialPopulation": " spl population"
},
"evc": {
"evcId": "evcid",
"action": "PR",
"serviceId": "assigned prod id",
"previousValues": {
"previousName":"evcId",
"previousValue":"EVC id - OLD"
},
"uni": [
{
"type": "uniA",
"uniId": "uni id",
"siteId": "sidt id",
"tspCode": "tsp code",
"elocId": "e loc id",
"siteClli": "site clli",
"uniAction": "PR",
"previousValues": {
"previousName":"evcId",
"previousValue":"EVC id - OLD"
}
},
{
"type": "uniZ",
"siteId": "sidt id",
"tspCode": "tsp code",
"elocId": "e loc id",
"siteClli": "site clli",
"uniAction": "PR",
"previousValues": {
"previousName":"evcId",
"previousValue":"EVC id - OLD"
}
}
]
},
"solutionType": "EPL",
"source": "Orion"
}
CPInput.java
public class CPInput {
private String customerId;
private CustomerSegment customerSegment;
private Evc evc;
private String solutionType;
private String source;
public CPInput() {
super();
}
public class CustomerSegment{
private String customerType;
private String customerSubtype;
private String industry;
private String subIndustry;
private String specialPopulation;
//getter setter
}
public class Evc{
private String evcId;
private String action;
private String serviceId;
private PreviousValues previousValues;
private List<CPInput.Evc.Uni> uni=new ArrayList<CPInput.Evc.Uni>();
//getter setter
public class PreviousValues{
private String previousName;
private String previousValue;
//getter setter
}
public class Uni{
private String type;
private String uniId;
private String siteId;
private String tspCode;
private String elocId;
private String siteClli;
private String uniAction;
private PreviousValues previousValues;
//getter setter
public class PreviousValues{
private String previousName;
private String previousValue;
//getter setter
}
//getter setter
}
DemoController.java
#RestController
#SpringBootApplication(scanBasePackages = {"com.test"})
#RequestMapping(value = "/demo")
public class DemoController {
#RequestMapping(method = RequestMethod.POST, value = "/addCustomer")
public CPOutput addCustomer(#RequestBody CPInput input) {
System.out.println(input);
return null;
}
}
Try to use static inner classes for: CustomerSegment, Evc, PreviousValues and Uni.
I always use static inner classes, and I don't have any problem like that.
I have the following JSON modelling groups with students:
"groups":[{
"id": "1",
"grade":"second",
"group": "A",
"students":[{
"id": "1",
"address": "rhonda#pugh.no",
"name": "Geoffrey Guthrie",
"phone": "475690",
"parent": "Ronald Zhang",
"diagnosis": "Whitehead",
},
...}],
...}]
and their respective classes are as follows (setters and getters not included):
public class Student extends RealmObject {
private String id;
private String name;
private String address;
private String phone;
private String parent;
private String diagnosis;
}
and:
public class Group extends RealmObject{
private String id;
private String grade;
private String group;
private RealmList<Student> students;
}
My question here is if the method createOrUpdateAllFromJson, as stated above, supports those nested arrays or should I do it manually getting the arrays inside and then call the same function to create the list of students for each group?
No you don't need to manually getting the arrays inside and then call the same function to create the list of students for each group. But you will not be able to use
createOrUpdateAllFromJson() for JOSNArray
or
createOrUpdateObjectFromJson() for JSONObject
Because createOrUpdate requires a primary key. But according to your Json structure there is no primary key for the root object. My code blocks will describe the scenario.
Your Json Structure-
{
"groups":[{
"id": "1",
"grade":"second",
"group": "A",
"students":[{
"id": "1",
"address": "rhonda#pugh.no",
"name": "Geoffrey Guthrie",
"phone": "475690",
"parent": "Ronald Zhang",
"diagnosis": "Whitehead"
}]
}]
}
According this Your Models should be as follows-
public class Students extends RealmObject {
private String id;
private String name;
private String address;
private String phone;
private String parent;
private String diagnosis;
}
and:
public class Groups extends RealmObject {
private String id;
private String grade;
private String group;
private RealmList<Students> students;
}
and:
public class BaseObject extends RealmObject {
private RealmList<Groups> groups;
}
And then your transaction will be like this-
realm.executeTransaction(new Realm.Transaction() {
#Override
public void execute(Realm realm) {
realm.createObjectFromJson(BaseObject.class, json);
}
});
You can add #PrimaryKey annotation for Groups and Students id to avoid duplicate entry if necessary. Hope this structure will reduce your hassle.
i have a String returned by a service, in this JSON format:
String message = {
"Tickets":
[{
"Type": "type1",
"Author": "author1",
"Rows":
[
{
"Price": "100.0",
"Date": "24/06/2016",
"Amount": "10"
},
{
"Type": "Comment",
"Value": "some comment goes here"
}
],
"ID": "165"
}],
"Desk": "desk1",
"User": "user1"
}
I need to parse it and convert into a Java object.
I tried to create a dom like this:
public class TicketWrapper{
private Ticket ticket;
private String desk;
private String user;
}
public class Ticket {
private String type;
private String author;
private List<Row> rows;
private String id;
}
public class Row1{
private float price;
private Date date;
private int amount;
}
public class Row2{
private String type;
private float value;
}
Then I try to parse it with Google Gson, this way:
TicketWrapper ticket = gson.fromJson(message, TicketWrapper.class)
but if I print it System.out.println(gson.toJson(ticket)), it prints:
{"desk" : 0, "user" : 0}
I don't know how to parse that Json into a Java Object, and how to tell him that a row into "Rows" can be of the Row1 type or Row2 type.
I think there is a few issues, such names of properties in lower case and dateformat and mix types of rows. I just changed like this and worked for me:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
import org.junit.Test;
import java.util.Date;
import java.util.List;
public class CheckTest {
#Test
public void thisTest() {
Gson gson = new GsonBuilder()
.setDateFormat("dd-MM-yyyy")
.setPrettyPrinting()
.create();
String message = "{\"Tickets\":" +
"[{\"Type\":\"type1\"," +
"\"Author\":\"author1\"," +
"\"Rows\":[{\"Price\":\"100.0\"," +
"\"Date\":\"24-06-2016\"," +
"\"Amount\":\"10\"}," +
"{\"Type\":\"Comment\"," +
"\"Value\":\"some comment goes here\"}]," +
"\"ID\":\"165\"}]," +
"\"Desk\":\"desk1\"," +
"\"User\":\"user1\"}";
TicketWrapper ticket = gson.fromJson(message, TicketWrapper.class);
System.out.println(ticket.toString());
}
public class TicketWrapper {
#SerializedName("Tickets")
private List<Ticket> tickets;
#SerializedName("Desk")
private String desk;
#SerializedName("User")
private String user;
public TicketWrapper() {
}
}
public class Ticket {
#SerializedName("Type")
private String type;
#SerializedName("Author")
private String author;
#SerializedName("Rows")
private List<Row> rows;
#SerializedName("ID")
private String id;
public Ticket() {
}
}
public class Row {
#SerializedName("Type")
private String type;
#SerializedName("Value")
private String value;
#SerializedName("Price")
private float price;
#SerializedName("Date")
private Date date;
#SerializedName("Amount")
private int amount;
public Row() {
}
}
}
As others have already mentioned in the comment, you need to make sure the mapping directly reflects the file names. It needs to be 'User' and 'Desk' instead of 'user' and 'desk'. Also, you have a list of tickets, which would map to List Tickets.
I want to parse my JSONObject with gson. I write some code but doesn't work.
public class User {
#SerializedName("Email")
public static String Email;
#SerializedName("Id")
public static int Id;
#SerializedName("Picture")
public static String Picture=null;
#SerializedName("UserName")
public static String UserName;
}
In my class:
User result=new Gson().fromJson(response,User.class);
My JSONObject:
{
"Email": "",
"Id": 1,
"Picture": null,
"UserName": "User1"
}
Remove static modifier from all variables and try it again.
Note: Make all variable private and provide public getter/setter methods. learn more...
I have a JSON file that I fetch from the internet which contains schedule data for a TV channel. Nested within that file, alongside lots of metadata, is info about each broadcast (i.e. each programme) and below is a sample of that file:
For ease of understanding, I recommend this visual representation of the below JSON instead (click on the Viewer tab on the JSON viewer).
{
"schedule": {
"service": {
"type": "tv",
"key": "bbcnews",
"title": "BBC News Channel"
},
"day": {
"date": "2013-11-15",
"has_next": 1,
"has_previous": 1,
"broadcasts": [
{
"is_repeat": false, <=== This is the 1st broadcast programme
"is_blanked": false,
"pid": "p01ks4z3",
"start": "2013-11-15T03:45:00Z",
"end": "2013-11-15T04:00:00Z",
"duration": 900,
"programme": {
"type": "episode",
"pid": "b03hdhhp",
"position": null,
"title": "15/11/2013",
"short_synopsis": "All the latest sports news and results from around the globe.",
"media_type": "audio_video",
"duration": 900,
"display_titles": {
"title": "Sport Today",
"subtitle": "15/11/2013"
},
"first_broadcast_date": "2013-11-15T03:45:00Z",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
},
"programme": {
"type": "brand",
"pid": "b0121xvw",
"title": "Sport Today",
"position": null,
"expected_child_count": null,
"first_broadcast_date": "2011-06-13T02:45:00+01:00",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
}
},
"is_available_mediaset_pc_sd": false,
"is_legacy_media": false
}
},
{
"is_repeat": false, <=== This is the 2nd broadcast programme
"is_blanked": false,
"pid": "p01ks4z4",
"start": "2013-11-15T04:00:00Z",
"end": "2013-11-15T04:30:00Z",
"duration": 1800,
"programme": {
"type": "episode",
"pid": "b03hdhhs",
"position": null,
"title": "15/11/2013",
"short_synopsis": "Twenty-four hours a day, the latest national and international stories as they break.",
"media_type": "audio_video",
"duration": 1800,
"display_titles": {
"title": "BBC News",
"subtitle": "15/11/2013"
},
"first_broadcast_date": "2013-11-15T04:00:00Z",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
},
"programme": {
"type": "brand",
"pid": "b006mgyl",
"title": "BBC News",
"position": null,
"expected_child_count": null,
"first_broadcast_date": "2006-11-01T13:00:00Z",
"ownership": {
"service": {
"type": "tv",
"id": "bbc_news24",
"key": "bbcnews",
"title": "BBC News Channel"
}
}
},
"is_available_mediaset_pc_sd": false,
"is_legacy_media": false
}
}
]
}
}
}
Using the answer to this question on StackOverflow, I created a Javabean class like so:
private class ScheduleData {
private Schedule schedule;
// create getter & setter
public static class Schedule {
private Service service;
private Day day;
// create getter & setter
}
public static class Service {
private String type;
private String key;
private String title;
// create getter & setter
}
public static class Day {
private String date;
private String has_next;
private String has_previous;
private Broadcasts broadcasts;
// create getter & setter
}
public static class Broadcasts {
private String is_repeat;
private String is_blanked;
private String pid;
private String time;
private String end;
private String duration;
private OuterProgramme programme;
// create getter & setter
}
public static class OuterProgramme {
private String type;
private String pid;
private String position;
private String title;
private String short_synopsis;
private String media_type;
private String duration;
private String first_broadcast_date;
private DisplayTitles display_titles;
private Ownership ownership;
private InnerProgramme programme;
// create getter & setter
}
public static class DisplayTitles {
private String title;
private String subtitle;
// create getter & setter
}
public static class Ownership {
private Service service;
// create getter & setter
}
public static class Service {
private String type;
private String id;
private String key;
private String title;
// create getter & setter
}
public static class InnerProgramme {
private String type;
private String pid;
private String title;
private String position;
private String expected_child_count;
private String first_broadcast_date;
private Ownership ownership;
private String is_available_mediaset_pc_sd;
private String is_legacy_media;
// create getter & setter
}
}
In my activity file, how do I loop through each broadcast node of the fetched JSON and retrieve programme data such as short_synopsis or display_titles and pass these into a custom listview display?
1) Define root Json Wrapper class ScheduleData.java
public class ScheduleData {
private Schedule schedule;
public Schedule getSchedule() {
return schedule;
}
}
2) Define its properties as seperate public classes:
2.a) Schedule.java
public class Schedule {
private Service service;
private Day day;
// TODO: create other getters & setters if you need
public Day getDay() {
return day;
}
}
2.b) Service.java
public class Service {
private String type;
private String id;
private String key;
private String title;
// TODO: create getters & setters if you need
}
2.c) Day.java
public class Day {
private String date;
private int has_next;
private int has_previous;
private Broadcast[] broadcasts;
// TODO: create other getters & setters if you need
public Broadcast[] getBroadcasts() {
return broadcasts;
}
}
2.d) Broadcast.java
public class Broadcast {
private boolean is_repeat;
private boolean is_blanked;
private String pid;
private String start;
private String end;
private int duration;
private Programme programme;
// TODO: create other getters & setters if you need
public Programme getProgramme() {
return programme;
}
}
2.e) Programme.java
public class Programme {
private String type;
private String pid;
private String position;
private String title;
private String short_synopsis;
private String media_type;
private int duration;
private String first_broadcast_date;
private DisplayTitle display_titles;
private Ownership ownership;
private Programme programme;
// TODO: create other getters & setters if you need
public String getShort_synopsis() {
return short_synopsis;
}
public DisplayTitle getDisplay_titles() {
return display_titles;
}
}
2.f) DisplayTitle.java
public class DisplayTitle {
private String title;
private String subtitle;
// create getter & setter
}
2.g) Ownership.java
public class Ownership {
private Service service;
// create getter & setter
}
3) Define an AsyncTask and call json service. Get result as stream and set its value to a ScheduleData instance using gson library. (I assume you know how to call json service on android, but if you don't it is a 5 min googling issue.)
HttpEntity getResponseEntity = getResponse.getEntity();
InputStream source = getResponseEntity.getContent();
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ScheduleData scheduleData = gson.fromJson(reader, ScheduleData.class);
4) Now you have a ScheduleData instance. It is filled by service's json response.
Schedule schedule = scheduleData.getSchedule();
Day day = schedule.getDay();
Broadcast[] broadCastArr = day.getBroadcasts();
// TODO: use your broadCastArr in an adapter