Related
I'm trying to populate a List<Object> that has as a attribute another List.
Here is The Scenario.
First Object
public class Student {
private String initials;
private String id;
private List<StudentDetail> listStudentDetail;
//Setters and Getters
}
Second Object
public class StudentDetail {
private String id;
private String name;
//Setters and getters
}
My final java object is as follows.
public class Response {
private String code;
private String message;
private List<Student> listStudent;
//Setters and getters
}
I get populated a List<Student>and a List<StudentDetail> from another process and what I want to achive is merge both list into my Response class but with theese particular conditions
In order to fill List<StudentDetail>
Student.initials must be "a"
Student.id = StudentDetail.id
These is what I want to Achieve.
{
"code": "0",
"message": "Succes",
"listStudent": [
{
"initials": "a",
"id": "104",
"listStudentDetail": [
{
"id": "104",
"name": "Kevin"
}
]
},
{
"initials": "b",
"id": "100",
"listStudentDetail": []
},
{
"initials": "a",
"id": "105",
"listStudentDetail": [
{
"id": "105",
"name": "Robert"
}
]
}
]
}
Here is the code.
I am assuming populatedStudentList and populatedStudentDetail as the given objects that have been populated in some other part of the code like you mentioned.
for (Student s in populatedStudentList){
if (s.getInitials().compareTo('a') != 0){
continue;
}
String findId = s.getId();
List<StudentDetail> tempListStudentDetail = new ArrayList<>();
for (StudentDetail d in populatedStudentDetail){
if (d.getId().compareTo(findId) == 0){
tempListStudentDetail.append(d);
}
}
s.setListStudentDetail(tempListStudentDetail);
}
This can be achieved in a more memory efficient manner using hashTables but I have tried to reproduce the desired result in the most basic manner.
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 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.
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 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()