Parsing JSON as Java Object is giving me some null values - java

I'm trying to convert a JSON object into a POJO class,
but some values are ending up with null values while
others are set to the value from the JSON.
The response is
{
"intention_id": 12936,
"intention_datetime": "2021-03-09T09:58:16-03:00",
"status": "created",
"cuit": "20-314559999-9",
"branch": "Avellaneda 13",
"checkout": "8",
"terminal_number": "87980012",
"intention_type": "payment",
"original_amount": 1200.0,
"currency": "ARS",
"payment_methods_data": [
{
"payment_method_id": 1,
"establishment_id": "29880765",
"trace_number": 1090,
"ticket_number": 131,
"installments": [
{
"quantity": 1,
"total_amount": 1200.0,
"amount_per_installment": 200.0,
"cft": 12.56,
"tna": 14.87
},
{
"bank_id": 28,
"quantity": 6,
"total_amount": 1200.0,
"amount_per_installment": 200.0,
"cft": 12.56,
"tna": 14.87
},
{
"quantity": 6,
"total_amount": 1400.0,
"amount_per_installment": 233.33,
"cft": 12.56,
"tna": 14.87
}
]
},
{
"payment_method_id": 15,
"establishment_id": "69880548",
"trace_number": 2034,
"ticket_number": 673,
"installments": [
{
"quantity": 1,
"total_amount": 1200.0,
"amount_per_installment": 200.0,
"cft": 12.56,
"tna": 14.87
},
{
"bank_id": 28,
"quantity": 6,
"total_amount": 1200.0,
"amount_per_installment": 200.0,
"cft": 12.56,
"tna": 14.87
},
{
"quantity": 6,
"total_amount": 1400.0,
"amount_per_installment": 233.33,
"cft": 12.56,
"tna": 14.87
}
]
}
],
"integrator_intention_id": "587cba61-ff27-46c6-ba8b-fd936665c35f",
"integrator": "alsea"
}
I'm ignoring the array elements,
so my Object Class is
public class ObjectResponseBimo {
public int intention_id;
public String intention_datetime;
public String status;
public String cuit;
public String branch;
public String checkout;
public String terminal_number;
public String intention_type;
public double original_amount;
public String currency;
public String integrator_intention_id;
public String integrator;
public int getIntention_id() {
return intention_id;
}
#JsonProperty("intention_id")
public void setIntention_id(int intention_id) {
this.intention_id = intention_id;
}
public String getIntention_datetime() {
return intention_datetime;
}
#JsonProperty("intention_datetime")
public void setIntention_datetime(String intention_datetime) {
this.intention_datetime = intention_datetime;
}
public String getStatus() {
return status;
}
#JsonProperty("status")
public void setStatus(String status) {
this.status = status;
}
public String getCuit() {
return cuit;
}
#JsonProperty("cuit")
public void setCuit(String cuit) {
this.cuit = cuit;
}
public String getBranch() {
return branch;
}
#JsonProperty("branch")
public void setBranch(String branch) {
this.branch = branch;
}
public String getCheckout() {
return checkout;
}
#JsonProperty("checkout")
public void setCheckout(String checkout) {
this.checkout = checkout;
}
public String getTerminal_number() {
return terminal_number;
}
#JsonProperty("terminal_number")
public void setTerminal_number(String terminal_number) {
this.terminal_number = terminal_number;
}
public String getIntention_type() {
return intention_type;
}
#JsonProperty("intention_type")
public void setIntention_type(String intention_type) {
this.intention_type = intention_type;
}
public double getOriginal_amount() {
return original_amount;
}
#JsonProperty("original_amount")
public void setOriginal_amount(double original_amount) {
this.original_amount = original_amount;
}
public String getCurrency() {
return currency;
}
#JsonProperty("currency")
public void setCurrency(String currency) {
this.currency = currency;
}
public String getIntegrator_intention_id() {
return integrator_intention_id;
}
#JsonProperty("integrator_intention_id")
public void setIntegrator_intention_id(String integrator_intention_id) {
this.integrator_intention_id = integrator_intention_id;
}
public String getIntegrator() {
return integrator;
}
#JsonProperty("integrator")
public void setIntegrator(String integrator) {
this.integrator = integrator;
}
#Override
public String toString() {
return "ObjectResponseBimo [intention_id=" + intention_id + ", intention_datetime=" + intention_datetime
+ ", status=" + status + ", cuit=" + cuit + ", branch=" + branch + ", checkout=" + checkout
+ ", terminal_number=" + terminal_number + ", intention_type=" + intention_type + ", original_amount="
+ original_amount + ", currency=" + currency + ", integrator_intention_id=" + integrator_intention_id
+ ", integrator=" + integrator + "]";
}}
All the other getter and setter,
everyone has JsonProperty in the set method
I'm working with Jackson,
so I'm sending the object with
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
ObjectResponseBimo o = objectMapper.readValue(jsonToPost, ObjectResponseBimo.class);
return objectMapper.toString() + "\n" + o.toString();
The output is:
ObjectResponseBimo [intention_id=0, intention_datetime=null,
status=null, cuit=20-314559999-9, branch=Avellaneda 13, checkout=8,
terminal_number=87980012, intention_type=payment,
original_amount=1200.0, currency=ARS,
integrator_intention_id=587cba61-ff27-46c6-ba8b-fd936665c35f,
integrator=null ]

The code you provided works fine. I have just copied it to the clean project and tested it.
I would give you couple of notes, not related to the question.
Class variables should be private, and for Jackson no need to have setters and getters to make json. It used reflection.
Class variables should be CamelCase. This is general practice in Java.
This is is, how your data class should look like:
public class ObjectResponseBimo {
#JsonProperty("intention_id")
private int intentionId;
#JsonProperty("intention_datetime")
private String intentionDatetime;
private String status;
private String cuit;
private String branch;
private String checkout;
#JsonProperty("terminal_number")
private String terminalNumber;
#JsonProperty("intention_type")
private String intentionType;
#JsonProperty("original_amount")
private double originalAmount;
private String currency;
#JsonProperty("integrator_intention_id")
private String integratorIntentionId;
private String integrator;
}
And to work with json, you could use a tool to hide all routinse. E.g. JacksonUtils:
ObjectResponseBimo obj = JacksonUtils.readValue(json, ObjectResponseBimo.class);
P.S. Repeat, code that you have provided works fine on the clean project. Probably you have a problem someqhere else, and this is only the side effect.

So I just tried to copy your code and made couple of changes.
Add below annotation at the top of your pojo class (ObjectResponseBimo.java)
**#JsonIgnoreProperties(ignoreUnknown = true)**
public class ObjectResponseBimo {
This will ignore the unknown properties from json having no match with equivalent java properties.
And for the object mapper, below snippet should be enough to get it work:
ObjectMapper objectMapper = new ObjectMapper();
ObjectResponseBimo ob = objectMapper.readValue(ClassLoader.getSystemResourceAsStream("ObjectResponseBimo.json"), ObjectResponseBimo.class);
System.out.println(ob.toString());
System.out.println(ob.getIntention_id() + " | " + ob.getBranch());
I am not sure why toString() is not working for you. It is working for me though.

Related

Put method using a mapped class (use setters for specified parameter) - Spring boot API

I'm trying to make a PUT request for an object using only one function for all parameters. Let's say I have this object structure (JSON):
{
"id": 3,
"name": "test",
"dominio": "dom",
"altas": "6",
"bajas": "2",
"default_group": [
{
"idRef": 1,
"name": "Users",
"path": "OU=es"
}
],
"office": [
{
"idRef": 1,
"title": "Intern",
"name": "CN=Office license",
"path": "OU=licenseOffice"
},
{
"idRef": 2,
"title": "Specialist",
"name": "CN=Office License F3",
"path": "OU=LicenseGroupF"
}
]
}
I managed to do this for a GET Request using a Map function with the getters of the class.
To do this, I passed the attribute name in the HTTP request using a GET Request:
Map<String, Function<Compania, Object>> mapCompania = Map.of(
"name", Compania::getName,
"dominio", Compania::getDominio,
"altas", Compania::getAltas,
"bajas", Compania::getBajas,
"default_group", Compania::getDefault_group,
"office", Compania::getOffice
);
Function<Compania, Object> retriever = mapCompania.get(fieldName);
But now, I can't find a way to implement this same thing but in order to use the setter methods. Something like:
PUT localhost/myClass/3/name --> it uses MyClass.setName(input...)
Or:
PUT localhost/myClass/3/office --> it uses MyClass.setOffice(Object office)
Could anyone help me to achieve this? Thank you very much
Assuming that Compania is as follows:
public class Compania {
private Object name;
private Object dominio;
private Object altas;
private Object bajas;
private Object default_group;
private Object office;
public Object getName() {
return name;
}
public void setName(Object name) {
this.name = name;
}
public Object getDominio() {
return dominio;
}
public void setDominio(Object dominio) {
this.dominio = dominio;
}
public Object getAltas() {
return altas;
}
public void setAltas(Object altas) {
this.altas = altas;
}
public Object getBajas() {
return bajas;
}
public void setBajas(Object bajas) {
this.bajas = bajas;
}
public Object getDefault_group() {
return default_group;
}
public void setDefault_group(Object default_group) {
this.default_group = default_group;
}
public Object getOffice() {
return office;
}
public void setOffice(Object office) {
this.office = office;
}
}
The code below should do the trick:
Map<String, BiConsumer<Compania, Object>> mapCompaniaSetters = Map.of(
"name", Compania::setName,
"dominio", Compania::setDominio,
"altas", Compania::setAltas,
"bajas", Compania::setBajas,
"default_group", Compania::setDefault_group,
"office", Compania::setOffice
);
BiConsumer<Compania, Object> setter = mapCompaniaSetters.get(fieldName);
We can test this as follows to check that it actually works:
public static void main(String[] args) {
Map<String, BiConsumer<Compania, Object>> mapCompaniaSetters = Map.of(
"name", Compania::setName,
"dominio", Compania::setDominio,
"altas", Compania::setAltas,
"bajas", Compania::setBajas,
"default_group", Compania::setDefault_group,
"office", Compania::setOffice
);
BiConsumer<Compania, Object> setter = mapCompaniaSetters.get("name");
Compania compania = new Compania();
System.out.println("Empty Compania: " + compania);
setter.accept(compania, "Test");
System.out.println("Compania with Name: " + compania);
}

How do I consume an array of JSON objects with Spring Boot?

With reference to this guide:
https://spring.io/guides/gs/consuming-rest/
The guide shows how to consume a RESTful web service.
The response from the REST API query results in the following JSON:
{
type: "success",
value: {
id: 10,
quote: "Really loving Spring Boot, makes stand alone Spring apps easy."
}
}
It creates a domain class called Quote.java to contain the data in the response:
package hello;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#JsonIgnoreProperties(ignoreUnknown = true)
public class Quote {
private String type;
private Value value;
public Quote() {
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
#Override
public String toString() {
return "Quote{" +
"type='" + type + '\'' +
", value=" + value +
'}';
}
}
My questions is how do I represent the following json:
{
"size": 1,
"limit": 25,
"isLastPage": true,
"values": [
{
"user": {
"name": "jcitizen",
"emailAddress": "jane#example.com",
"id": 101,
"displayName": "Jane Citizen",
"active": true,
"slug": "jcitizen",
"type": "NORMAL"
},
"permission": "ADMIN"
}
],
"start": 0
}
The outer objects like size and limit are straightforward but I can't figure out how to represent the values object, which looks like an array of json objects.
This should work.
class Output {
private String size,
private int limit;
private boolean isLastPage,
private List<Value> values;
private int start ;
}
class Value
{
User user,
private String permission;
}
class User {
private String name,
private String emailAddress,
private int id,
private String displayName,
private boolean active,
private String slug,
private String type
}

Correct JSON response for Retrofit+GSON?

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.

Mapping JSON String to a POJO with Jackson gives null values

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"
}
}

How to convert JSON objects to POJO from Gson

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()

Categories