I have below response for one of my web service and I'm using Retrofit and GSON.
{
"error": false,
"Timeline": {
"Date": "2040-06-15",
"bandList": {
"breakfast": {
"dosageList": {
"01": {
"packed": "true",
"medicineList": [
{
"medicine": {
"id": "01",
"name": "glipizide 5 mg tablet, 100 ",
"category": "regular",
"image": null,
"indication": "NIDDM",
"packed": true,
"med_id": "352",
"dosage": 1
}
},
{
"medicine": {
"id": "04",
"name": "Frusemide (Terry White Chemists) 20 mg uncoated tablet, 100 ",
"category": "regular",
"image": null,
"indication": "Fluid",
"packed": true,
"med_id": "4",
"dosage": 2
}
}
]
},
"02": {
"packed": "false",
"medicineList": [
{
"medicine": {
"id": "05",
"name": "Refresh Tears Plus 0.5% eye drops solution, 15 mL ",
"category": "regular",
"image": null,
"indication": "Dry Eyes",
"packed": false,
"med_id": "372",
"dosage": 1
}
}
]
}
}
}
}
}
}
Q1.
Is there a way to parse above response using model classes (POJOs) or without them? I'm stuck at generating model classes for above structure. How do I generate POJOs for above JSON?
Q2. I'm in a position how to convince to send below response, what is the correct structure/format for JSON? Is there any JSON standard I could show to the web developer to get this JSON format? (note:I'm okay to parse this structure)
{
"error": false,
"Timeline": {
"Date": "2040-06-15",
"band": [
{
"name": "breakfast",
"dosage": [
{
"id": "01",
"packed": "true",
"medicine": [
{
"id": "01",
"name": "glipizide 5 mg tablet, 100 ",
"category": "regular",
"image": null,
"indication": "NIDDM",
"packed": true,
"med_id": "52",
"dosage": 1
},
{
"id": "04",
"name": "Frusemide (Terry White Chemists) 20 mg uncoated tablet, 100 ",
"category": "regular",
"image": null,
"indication": "Fluid",
"packed": true,
"med_id": "54",
"dosage": 2
}
]
},
{
"id": "02",
"packed": "false",
"medicine": [
{
"id": "05",
"name": "Refresh Tears Plus 0.5% eye drops solution, 15 mL ",
"category": "regular",
"image": null,
"indication": "Dry Eyes",
"packed": false,
"med_id": "372",
"dosage": 1
}
]
}
]
}
]
}
}
Thank you in advance.
EDIT
I use to autogenerate POJOs using those sites, but its giving below responses for some classes. How do I convert this to proper class?
package ;
public class DosageList
{
private 01 01;
private 02 02;
public void set01(01 01){
this.01 = 01;
}
public 01 get01(){
return this.01;
}
public void set02(02 02){
this.02 = 02;
}
public 02 get02(){
return this.02;
}
}
EDIT 2
I have almost done parsing first JSON, but stuck in here.
for (String bandName: event.getTimeline().getBand().keySet()) {
Log.d("<<<--Band-->>>", "Value " + event.getTimeline().getBand().get(bandName));
Band band = event.getTimeline().getBand().get(bandName);
for (String dosageName:band.getDosage().keySet()) {
Dosage dosage = band.getDosage().get(dosageName);
Log.d("<<<--Dosage-->>>", "Value " + dosage.getMedicine());
for (Medicine medicine: dosage.getMedicine()) {
Log.d("<<<--Medicine-->>>", "Value " + dosage.getMedicine().get(0));
}
}
}
How do I retrieve medicine values?
public class Medicine
{
private String id;
private String name;
private String category;
private String image;
private String indication;
private boolean packed;
private String med_id;
private int dosage;
public void setId(String id){
this.id = id;
}
public String getId(){
return this.id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setCategory(String category){
this.category = category;
}
public String getCategory(){
return this.category;
}
public void setImage(String image){
this.image = image;
}
public String getImage(){
return this.image;
}
public void setIndication(String indication){
this.indication = indication;
}
public String getIndication(){
return this.indication;
}
public void setPacked(boolean packed){
this.packed = packed;
}
public boolean getPacked(){
return this.packed;
}
public void setMed_id(String med_id){
this.med_id = med_id;
}
public String getMed_id(){
return this.med_id;
}
public void setDosage(int dosage){
this.dosage = dosage;
}
public int getDosage(){
return this.dosage;
}
}
import java.util.ArrayList;
import java.util.List;
public class Dosage
{
private String id;
private String packed;
private List<Medicine> medicine;
public void setId(String id){
this.id = id;
}
public String getId(){
return this.id;
}
public void setPacked(String packed){
this.packed = packed;
}
public String getPacked(){
return this.packed;
}
public void setMedicine(List<Medicine> medicine){
this.medicine = medicine;
}
public List<Medicine> getMedicine(){
return this.medicine;
}
}
import java.util.ArrayList;
import java.util.List;
public class Band
{
private String name;
private List<Dosage> dosage;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setDosage(List<Dosage> dosage){
this.dosage = dosage;
}
public List<Dosage> getDosage(){
return this.dosage;
}
}
import java.util.ArrayList;
import java.util.List;
public class Timeline
{
private DateTime Date;
private List<Band> band;
public void setDate(DateTime Date){
this.Date = Date;
}
public DateTime getDate(){
return this.Date;
}
public void setBand(List<Band> band){
this.band = band;
}
public List<Band> getBand(){
return this.band;
}
}
public class Root
{
private boolean error;
private Timeline Timeline;
public void setError(boolean error){
this.error = error;
}
public boolean getError(){
return this.error;
}
public void setTimeline(Timeline Timeline){
this.Timeline = Timeline;
}
public Timeline getTimeline(){
return this.Timeline;
}
}
...enjoy...
For first question:
You can parse JSON without POJO classes but it is recommended to use
them and About you are stucking about generating them from the JSON
you can use jsonschema2pojo I think
it is the best.
And for the second one:
Yest there are standards for JSON you can find them in JSON website.
Step 1 : First start with the inner most json object which I can see is "medicine"
Create a POJO class something like this
public class Medicine implements android.os.Parcelable {
#SerializedName("id")
private String id;
// Getter setter method for id
// Do it for all the JSON tags
}
Step 2 : Create a class for "medicineList" this will somewhat be like this
public class MedicineList implements Parcelable {
#SerializedName("medicineList")
private List<Medicine > medicine;
// Getter setter can go here
}
In the similar fashion just move outside to your base tag in JSON response. This make things pretty easy for me to understand. I am not posting to the complete solution as thats your homework at EOD.
the solution for Q1 -
Yes, you can parse above response using model classes by installing the DTO plugin in the Android Studio. The plugin will automatically create the POJO class for the response.
Related
My Use case is I have a json file but I have to share only few of them to client.
Ex: Consider the source json file as shown below.
{
"name": "XYZ",
"age": 24,
"education": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
},
"friends": ["kkkk",
"bbbbbbbbbbb",
"jjjjjj"],
"dob":"01-08-1990"
}
For client 1 I have to share below output
{
"personalInfo": {
"name": "XYZ",
"age": 24,
"friendsNames": ["kkkk","bbbbbbbbbbb","jjjjjj"]
},
"educationalInfo": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
}
}
For client 2 I have to share below output
{
"personalInformation": {
"nameOfEmployee": "XYZ",
"ageOfEmployee": 24
},
"educationalInformation": {
"college": "ppppp",
"study": "b.tech"
}
}
And for other clients also the use case is same, I have to skip some keys and give different names to the keys. How to dynamically do this by some kind of configuration. I used jsonPath to achieve this but removing few keys from json object is difficult. Any suggestions can be appreciated.
Use a JSON Path library, like JayWay. With that, templates to transform your exapmle would be:
Client 1
{
"personalInfo": {
"name": "$.name",
"age": "$.age",
"friendsNames": "$.friends"
},
"educationalInfo": "$.education"
}
Client 2
{
"personalInformation": {
"nameOfEmployee": "$.name",
"ageOfEmployee": "$.age"
},
"educationalInformation": {
"college": "$.education.college",
"study": "$.education.study"
}
}
What you need to implement is the template traversal. It's about 20 lines of code; or 40 if you also need to transform list elements, like:
{
"friends": [ "$.friends[?(# =~ /.{5,}/)]", {
"name": "#",
"since": "$.dob"
} ]
}
which would result into:
{
"friends": [ {
"name": "bbbbbbbbbbb",
"since": "01-08-1990"
}, {
"name": "jjjjjj",
"since": "01-08-1990"
} ]
}
You can use Jackson to serialize and deserialize json. I suggest you to create seperate classes which represents your client data.
I show you an example of how you can deserialize your data and map it to your client json.
You can generate corresponding classes for client 2 with getting some help from http://www.jsonschema2pojo.org/ for mapping json to pojo.
Here is the code :
public class Main {
public static void main(String[] args) throws ParseException, ParserConfigurationException, IOException, SAXException {
ObjectMapper mapper = new ObjectMapper();
Root root = mapper.readValue(new File("test.json"), Root.class);
Client1 c1 = new Client1();
PersonalInfo personalInfo1 = new PersonalInfo();
personalInfo1.setAge(root.getAge());
personalInfo1.setFriendsNames(root.getFriends());
personalInfo1.setName(root.getName());
EducationalInfo educationalInfo1 = new EducationalInfo();
educationalInfo1.setCollege(root.getEducation().getCollege());
educationalInfo1.setGrade(root.getEducation().getGrade());
educationalInfo1.setStudy(root.getEducation().getStudy());
c1.setPersonalInfo(personalInfo1);
c1.setEducationalInfo(educationalInfo1);
mapper.writeValue(new File("client1.json"), c1);
}
}
Inside test.json file :
{
"name": "XYZ",
"age": 24,
"education": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
},
"friends": [
"kkkk",
"bbbbbbbbbbb",
"jjjjjj"
],
"dob": "01-08-1990"
}
Inside client1.json file :
{
"personalInfo": {
"name": "XYZ",
"age": 24,
"friendsNames": [
"kkkk",
"bbbbbbbbbbb",
"jjjjjj"
]
},
"educationalInfo": {
"college": "ppppp",
"study": "b.tech",
"grade": 6.8
}
}
Here is the classes which represents your json data:
class Education {
private String college;
private String study;
private float grade;
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getStudy() {
return study;
}
public void setStudy(String study) {
this.study = study;
}
public float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
}
// root of your base json data
class Root {
private String name;
private int age;
private Education education;
private List<String> friends;
private String dob;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Education getEducation() {
return education;
}
public void setEducation(Education education) {
this.education = education;
}
public List<String> getFriends() {
return friends;
}
public void setFriends(List<String> friends) {
this.friends = friends;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
}
class EducationalInfo {
private String college;
private String study;
private float grade;
public String getCollege() {
return college;
}
public void setCollege(String college) {
this.college = college;
}
public String getStudy() {
return study;
}
public void setStudy(String study) {
this.study = study;
}
public float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
}
// class which represents client 1 json data
class Client1 {
private PersonalInfo personalInfo;
private EducationalInfo educationalInfo;
public PersonalInfo getPersonalInfo() {
return personalInfo;
}
public void setPersonalInfo(PersonalInfo personalInfo) {
this.personalInfo = personalInfo;
}
public EducationalInfo getEducationalInfo() {
return educationalInfo;
}
public void setEducationalInfo(EducationalInfo educationalInfo) {
this.educationalInfo = educationalInfo;
}
}
class PersonalInfo {
private String name;
private int age;
private List<String> friendsNames = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getFriendsNames() {
return friendsNames;
}
public void setFriendsNames(List<String> friendsNames) {
this.friendsNames = friendsNames;
}
}
What about converting it to XML then create some XSLT? it might be much readable and cleaner.
I push full worked example in java into GIT with libs (lombok and jackson)
Template json mapped to object and object to json with different clients.
Your job is to output multilevel JSON data as multiple JSON formats. JSONPath can do this but the process is a hassle.
A simple alternative is to use SPL. SPL is a Java open-source package. You just need three lines of code to get the job done:
enter image description here
SPL offers JDBC driver to be invoked by Java. Just store the above SPL script as jsonparse.splx and invoke it in a Java application as you call a stored procedure:
…
Class.forName("com.esproc.jdbc.InternalDriver");
con= DriverManager.getConnection("jdbc:esproc:local://");
st = con.prepareCall("call jsonparse()");
st.execute();
…
Java doesn't have great templating built in.
But if you want to do a quick an dirty JSON template where you can replace a few values -- especially without all that ugly quote escaping:
{"key":"value"}
You can use single quotes and string replace:
{'key':'VALUE'}.replace("'", """).replace("VALUE", 42)
A few caveats:
This will break if any existing keys or values have single quotes (like O'malley).
It won't replace strings with numbers, boolean, or null
It can't -- by itself -- insert nested arrays or objects (e.g. [] {}) other than as strings.
But with a little bit of of extra work, you can accomplish the 80/20 rule. After that point you'd probably want to look into parsing or generating -- but by then you're not looking for a quick template.
I am trying to read some values under "properties" of following JSON string to a POJO. But all I get is null values.
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
144.9798,
-37.743
]
},
"properties": {
"PFI": "51351644",
"EZI_ADD": "581 BELL STREET COBURG 3058",
"ROAD_NAME": "BELL",
"ROAD_TYPE": "STREET",
"LOCALITY": "COBURG",
"LGA_CODE": "316",
"STATE": "VIC",
"POSTCODE": "3058",
"ADD_CLASS": "S"
},
"id": "ADDRESS.581"
}
My POJO class
#JsonIgnoreProperties(ignoreUnknown = true)
class Property {
public Property(){}
private String EZI_ADD; // e.g., "14 FAIRWAY COURT BUNDOORA 3083"
private String STATE; // e.g., "VIC"
private String POSTCODE; // e.g., "3083"
private String LGA_CODE; // e.g., 373
private String LOCALITY; // e.g., "BUNDOORA"
private String ADD_CLASS; // e.g., "S", or "M"
private String SA1_7DIG11 = ""; // SA1 code e.g., "2120241"
public String getEZI_ADD() {
return EZI_ADD;
}
#JsonProperty("EZI_ADD")
public void setEZI_ADD(String eZI_ADD) {
EZI_ADD = eZI_ADD;
}
public String getSTATE() {
return STATE;
}
#JsonProperty("STATE")
public void setSTATE(String sTATE) {
STATE = sTATE;
}
public String getPOSTCODE() {
return POSTCODE;
}
#JsonProperty("POSTCODE")
public void setPOSTCODE(String pOSTCODE) {
POSTCODE = pOSTCODE;
}
public String getLGA_CODE() {
return LGA_CODE;
}
#JsonProperty("LGA_CODE")
public void setLGA_CODE(String lGA_CODE) {
LGA_CODE = lGA_CODE;
}
public String getLOCALITY() {
return LOCALITY;
}
#JsonProperty("LOCALITY")
public void setLOCALITY(String lOCALITY) {
LOCALITY = lOCALITY;
}
public String getADD_CLASS() {
return ADD_CLASS;
}
#JsonProperty("ADD_CLASS")
public void setADD_CLASS(String aDD_CLASS) {
ADD_CLASS = aDD_CLASS;
}
public String getSA1_7DIG11() {
return SA1_7DIG11;
}
#JsonProperty("SA1_7DIG11")
public void setSA1_7DIG11(String sA1_7DIG11) {
SA1_7DIG11 = sA1_7DIG11;
}
}
Conversion code is as follows
//Above json string
String jsonString = "{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[144.9798,-37.743]},\"properties\":{\"PFI\":\"51351644\",\"EZI_ADD\":\"581 BELL STREET COBURG 3058\",\"ROAD_NAME\":\"BELL\",\"ROAD_TYPE\":\"STREET\",\"LOCALITY\":\"COBURG\",\"LGA_CODE\":\"316\",\"STATE\":\"VIC\",\"POSTCODE\":\"3058\",\"ADD_CLASS\":\"S\"},\"id\":\"ADDRESS.581\"}";
ObjectMapper mapper = new ObjectMapper();
Property properties = mapper.readValue(jsonString, Property.class);
Output:
{
"properties": {
"EZI_ADD": null,
"STATE": null,
"POSTCODE": null,
"LGA_CODE": null,
"LOCALITY": null,
"ADD_CLASS": null,
"SA1_7DIG11": ""
}
}
The JSON String you're sending does not match the Property class. Add a wrapper class, e.g. something like this:
public class Feature {
private String type;
private String id;
private Property property;
// getters and setters
}
Then you can send the request and the JSON String will be parsed to your object:
{
"type": "feature",
"id": "test",
"property": {
"PFI": "51351644",
"EZI_ADD": "581 BELL STREET COBURG 3058",
"ROAD_NAME": "BELL",
"ROAD_TYPE": "STREET",
"LOCALITY": "COBURG",
"LGA_CODE": "316",
"STATE": "VIC",
"POSTCODE": "3058",
"ADD_CLASS": "S"
}
}
I have two files: occupations.json and people.json. The former is just an array of occupations:
[
{ "name": "director", "pay": "100000"},
{ "name": "programmer", "pay": "75000"},
{ "name": "teacher", "pay": "50000"}
]
And the latter an array of a few people along with their occupation:
[
{ "name": "Mary", "occupation": "programmer" },
{ "name": "Jane", "occupation": "director" },
{ "name": "John", "occupation": "teacher" }
]
And these are the corresponding classes:
public class Occupation {
private final String name;
private final int pay;
public String getName() { ... }
public int getPay() { ... }
}
public class Person {
private final String name;
private final Occupation occupation;
public String getName() { ... }
public String getOccupation() { ... }
}
Currently I'm using ObjectMapper.readValue(InputStream, Class) to
unserialize the files. How can I make Person class aware of all existing Occupation objects? I want to select which occupation a person has by using the occupation's name.
add a function to Person.class
public Occupation getOccupation_()
{
// assume you had a static occupations list...
for (Occupation o : occupations)
if (o.name == this.occupation)
return o;
return null;
}
I am trying to convert JSON objects to POJO's with GSON.
JSON String
[
{
"automation_project": {
"user_id": null,
"name": "Untitled Project",
"updated_at": "2015-06-16T19:39:42Z",
"group_id": 764496,
"created_at": "2014-11-23T01:01:59Z",
"id": 16214
}
},
{
"automation_project": {
"user_id": null,
"name": "newintropage",
"updated_at": "2015-06-16T21:20:47Z",
"group_id": 764496,
"created_at": "2015-06-16T20:39:04Z",
"id": 29501
}
}
]
The AutomationProjectsList class used with GSON
public class AutomationProjectsList {
private List<AutomationProject> automationProject = new ArrayList<AutomationProject>();
public List<AutomationProject> getAutomationProject() {
return automationProject;
}
public void setAutomationProject(List<AutomationProject> automationProject) {
this.automationProject = automationProject;
}
#Override
public String toString() {
return "AutomationProjectsList [automationProject=" + automationProject
+ "]";
}}
Automation Project POJO
public class AutomationProject {
private Object userId;
private Integer groupId;
private Integer id;
private String name;
private String updatedAt;
private String createdAt;
public Object getUserId() {
return userId;
}
public void setUserId(Object userId) {
this.userId = userId;
}
public Integer getGroupId() {
return groupId;
}
public void setGroupId(Integer groupId) {
this.groupId = groupId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(String updatedAt) {
this.updatedAt = updatedAt;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}}
The code I'm using
JSONArray jsonArray = new JSONArray(response.getEntity(String.class));
for(int i = 0; i < jsonArray.length(); i++){
if(jsonArray.get(i) instanceof JSONObject){
JSONObject jsnObj = (JSONObject)jsonArray.get(i);
AutomationProjectsList obj = new Gson().fromJson(jsnObj.toString(), AutomationProjectsList.class);
System.out.println(obj.getAutomationProject().get(0).getId());
}
}
But it gives an exception :
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at br.usp.icmc.teste.ConnectionRestClient.getBrowserStackProjects(ConnectionRestClient.java:74)
at br.usp.icmc.teste.TestePrincipal.main(TestePrincipal.java:9)
Why am I receiving an IndexOutOfBoundsException exception? Where am I wrong?
Your class or your JSON are incorrect. I'd suggest your JSON is.
A JSON matching your POJO class would be:
{
"automationProjects":[
{
"user_id": null,
"name": "Untitled Project",
"updated_at": "2015-06-16T19:39:42Z",
"group_id": 764496,
"created_at": "2014-11-23T01:01:59Z",
"id": 16214
},
{
"user_id": null,
"name": "newintropage",
"updated_at": "2015-06-16T21:20:47Z",
"group_id": 764496,
"created_at": "2015-06-16T20:39:04Z",
"id": 29501
}
]
}
Notice I used the name automationProjects for the list as it makes more sense, so your class would be:
public class AutomationProjectsList {
private List<AutomationProject> automationProjects = new ArrayList<AutomationProject>();
public List<AutomationProject> getAutomationProjects() {
return automationProjects;
}
public void setAutomationProjects(List<AutomationProject> automationProjects) {
this.automationProjects = automationProjects;
}
#Override
public String toString() {
return "AutomationProjectsList [automationProject=" + automationProject
+ "]";
}
}
And finally to convert JSON to AutomationProjectsList object:
AutomationProjectsList projectsList = new Gson().fromJson(jsonArray.toString(), AutomationProjectsList.class);
Then if you want to log each project:
for(AutomationProject project : projectsList.automationProjects){
System.out.println(porject.getId());
}
In conclusion, your code seems to have the fallowing issues:
Do you have a list of lists or just a single list of projects? If the list is just one, why do you iterate jsonArray like its sub-objects are lists themselves?
If you model your class correctly on the JSON then you don't need to iterate the JSON to obtain your objects
The JSON you posted is quite weird and uneasy to use with Gson, is it a requirement or can you edit it as you please?
Hope this helps
EDIT
Since you stated you cannot change the JSON you get, then it gets a little more complex, but everything is up to modelling the classes on the JSON format. So let's start form this JSON:
[
{
"automation_project": {
"user_id": null,
"name": "Untitled Project",
"updated_at": "2015-06-16T19:39:42Z",
"group_id": 764496,
"created_at": "2014-11-23T01:01:59Z",
"id": 16214
}
},
{
"automation_project": {
"user_id": null,
"name": "newintropage",
"updated_at": "2015-06-16T21:20:47Z",
"group_id": 764496,
"created_at": "2015-06-16T20:39:04Z",
"id": 29501
}
}
]
Now, this is quite nasty, but let's see what we have here: we have an unnamed array of objects with a single attribute "automationProject" which is our actual AutomationProject Object. So in terms of structure, it is a list of objects which wrap an actual AutomationProject.
Thus you'll need to get rid of your AutomationProjectList and change it with the more meaningful AutomationProjectWrapper looking as fallows:
public class AutomationProjectsWrapper {
private AutomationProject automation_project = new AutomationProject();
public AutomationProject getAutomationProject() {
return automation_project;
}
public void setAutomationProject(AutomationProject automationProject) {
this.automation_project = automationProject;
}
#Override
public String toString() {
return "AutomationProjectsList [automationProject=" + automation_project
+ "]";
}
}
See this class is equivalent to the JSON Object:
{
"automation_project": {
"user_id": null,
"name": "Untitled Project",
"updated_at": "2015-06-16T19:39:42Z",
"group_id": 764496,
"created_at": "2014-11-23T01:01:59Z",
"id": 16214
}
}
Finally you'll have an array of such wrapper objects as your jsonArray so you can write:
AutomationProjectWrapper[] projectsList = new Gson().fromJson(jsonArray.toString(), AutomationProjectWrapper[].class);
Then to log your objects:
for(AutomationProjectWrapper wrapper : projectsList){
System.out.println(wrapper.getAutomationProject().getId());
}
EDIT 2
Sorry for the mistake, in AutomationProjectWrapper class the AutomationProject field should be named automation_project.
Fixed in code above.
According to your JSON String the value you are trying to access is :
jsonString[i].automation_project.user_id
In your code you have: obj.getAutomationProject().get(0).getId()
I think is should be: obj[i].getAutomationProject().getId()
I've managed to get many fields (id, title, date, etc) from the json files I'm working with but when it comes to the participants field, i can't seem to get it working. How do i get the participants arraylist working along with the other fields? Heres my code:
Application.java
package mypackage;
import mypackage.Objects;
import mypackage.Participation;
import mypackage.Participant;
import mypackage.Role;
import mypackage.utility.FileFinder;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Path;
import java.util.List;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Application implements Serializable{
static final long serialVersionUID = 1L;
public static void main(String[] args) {
try {
//Run configuration 'parse' - finds all objects within 682/456 - 21 in total
String objectsFile = args[0];
List<Path> files1 = FileFinder.getFileList(objectsFile, "*.json");
for (Path f : files1) {
Objects objects = new ObjectMapper().readValue(f.toFile(), Objects.class);
System.out.printf("Processing Object file: %s...", objectsFile);
System.out.println(objects.toString() + "\n" +
"-------------------------------------------------------------------"
+ "-------------------------------------------------------------------" );
}
}
catch (JsonParseException e) {
System.out.println("Error parsing the file.");
} catch (JsonMappingException e) {
System.out.println("Error mapping to Java object.");
} catch (IOException e) {
System.out.println("Unknown I/O error.");
}
}
}
Run Configurations > Argument (link to json files)
/Users/mycomputer/Documents/JavaWorkspace/git/collection/objects/682/456
objects.java
package mypackage;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
public class Objects {
private int id;
private String title;
private String date;
private String medium;
private String creditline;
private String description;
private String gallery_text;
#Override
public String toString() {
String objectsAsString = "\nID: " + id
+ "\nTitle: " + title
+ "\nDate: " + date
+ "\nMedium: " + medium
+ "\nCredit: " + creditline
+ "\nDescription: " + description
+ "\nGallery Text: " + gallery_text
;
return objectsAsString;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getMedium() {
return medium;
}
public void setMedium(String medium) {
this.medium = medium;
}
public String getCreditline() {
return creditline;
}
public void setCreditline(String creditline) {
this.creditline = creditline;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getGallery_text() {
return gallery_text;
}
public void setGallery_text(String gallery_text) {
this.gallery_text = gallery_text;
}
}
Console Output
Processing Object file: /Users/Joewinfield/Documents/JavaWorkspace/git/collection/objects/682/456...
ID: 68245603
Title: Note Card, New Institue Flyer, 2013
Date: 2013
Medium: Offset lithograph on paper
Credit: Gift of Karel Martens
Description: Black flyer with white text and three holes.
Gallery Text: null
--------------------------------------------------------------------------------------------------------------------------------------
Processing Object file: /Users/Joewinfield/Documents/JavaWorkspace/git/collection/objects/682/456...
ID: 68245607
Title: Mailer, New Institute Announcement, 2013
Date: 2013
Medium: Offset lithograph on paper
Credit: Gift of Karel Martens
Description: Black folded announcement printed with white text.
Gallery Text: null
Example json file
{
"id": "68245603",
"tms:id": "276634",
"accession_number": "2014-2-4",
"title": "Note Card, New Institue Flyer, 2013",
"title_raw": "New Institue Flyer",
"url": "http:\/\/collection.cooperhewitt.org\/objects\/68245603\/",
"department_id": "35347493",
"period_id": null,
"media_id": "35399021",
"type_id": "68245601",
"date": "2013",
"year_start": 2013,
"year_end": 2013,
"year_acquired": "2014",
"decade": "2010",
"woe:country_id": "23424909",
"medium": "Offset lithograph on paper",
"markings": null,
"signed": null,
"inscribed": null,
"provenance": "Karel Martens; 2014: acquired by Museum",
"dimensions": "21 x 10.5 cm (8 1\/4 x 4 1\/8 in.)",
"dimensions_raw": {
"height": [
"21.00",
"centimeters"
],
"width": [
"10.50",
"centimeters"
]
},
"creditline": "Gift of Karel Martens",
"description": "Black flyer with white text and three holes.",
"justification": "When Martens is asked how much do you need to represent something, his answer is \"no more than necessary.\" What drives his work is sparsity, limitation, constraint. This attitude is perfectly expressed in the interim identity he designed for the New Institute (launched 2013), which combines three existing institutions: The Netherlands Architecture Institute (NAI); Premsela, The Netherlands Institute for Design and Fashion; and Virtueel Platform, for e-culture. With no money available for the intervention, Martens took the graphic identity designed by Bruce Mau for the Netherlands Architecture Institute (represented in the CHNDM collection, 2000-43-1\/13) and printed over it in black, allowing enough of the old identity to show through to reveal the history behind the project, and then punched or printed three holes in the paper or envelope to represent the united institutions. As the New Institute press release stated, \"With Martens\u2019 design, history is not only visible but it is also literally given a new layer, symbolizing a new mission and ambition.\" From the New Institute identity campaign, Mr. Martens is donating eighteen pieces. This campaign provides a nice process story, since it demonstrates the transition from the logo material prepared by Bruce Mau to the New Institute, allowing us to see how a company or non-profit adjusts a prior graphic design campaign given a change in mission or circumstance.",
"gallery_text": null,
"label_text": null,
"videos": null,
"on_display": null,
"woe:country": "23424909",
"type": "Note card",
"images": [
{
"b": {
"url": "https:\/\/images.collection.cooperhewitt.org\/87603_ae15c6c8f5c06f3d_b.jpg",
"width": 511,
"height": 1024,
"is_primary": "1",
"image_id": "87603"
},
"z": {
"url": "https:\/\/images.collection.cooperhewitt.org\/87603_ae15c6c8f5c06f3d_z.jpg",
"width": 319,
"height": 640,
"is_primary": "1",
"image_id": "87603"
},
"n": {
"url": "https:\/\/images.collection.cooperhewitt.org\/87603_ae15c6c8f5c06f3d_n.jpg",
"width": 160,
"height": 320,
"is_primary": "1",
"image_id": "87603"
},
"d": {
"url": "https:\/\/images.collection.cooperhewitt.org\/87603_ae15c6c8f5c06f3d_d.gif",
"width": 160,
"height": 320,
"is_primary": "1",
"image_id": "87603"
},
"sq": {
"url": "https:\/\/images.collection.cooperhewitt.org\/87603_ae15c6c8f5c06f3d_sq.jpg",
"width": 300,
"height": 300,
"is_primary": "1",
"image_id": "87603"
}
}
],
"participants": [
{
"person_id": "18064377",
"role_id": "35351535",
"person_name": "Karel Martens",
"person_date": "Dutch, b. 1939",
"role_name": "Donor",
"role_display_name": "Donated by",
"person_url": "http:\/\/collection.cooperhewitt.org\/people\/18064377\/",
"role_url": "http:\/\/collection.cooperhewitt.org\/roles\/35351535\/"
},
{
"person_id": "18064377",
"role_id": "35236655",
"person_name": "Karel Martens",
"person_date": "Dutch, b. 1939",
"role_name": "Designer",
"role_display_name": "Designed by",
"person_url": "http:\/\/collection.cooperhewitt.org\/people\/18064377\/",
"role_url": "http:\/\/collection.cooperhewitt.org\/roles\/35236655\/"
}
],
"tombstone": {
"epitaph": "Note Card, New Institue Flyer, 2013. Offset lithograph on paper. \nGift of Karel Martens. 2014-2-4."
},
"colors": [
],
"woe:country_name": "Netherlands"
}
If I understood your question correctly, you just need to define the list of participants in your Objects class. I don't see in your code how you defined the participants, and the error you get.
A quick example for you, having the class Object:
public class Object {
private int id;
private String title;
private String date;
private List<Participants> participants;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List<Participants> getParticipants() {
return participants;
}
public void setParticipants(List<Participants> participants) {
this.participants = participants;
}
}
And the class Participants:
public class Participants {
private String person_name;
public String getPerson_name() {
return person_name;
}
public void setPerson_name(String person_name) {
this.person_name = person_name;
}
}
For the JSON file:
{
"id": "68245603",
"title": "Note Card, New Institue Flyer, 2013",
"date": "2013",
"participants": [
{
"person_name": "Karel Martens"
},
{
"person_name": "Karel Martens"
}
]
}
The code:
Object objects = new ObjectMapper().readValue(jsonFIle, Object.class);
will populate your Object with participants as well.