parse JSON local file in java with Gson library - java

I have this JSON file:
{
"mapping": {
"trips": [
{
"starttime": "15:10:50.000",
"endtime": "15:17:30.000",
"name": "island1",
"program": [
{
"starttime": "15:14:27.000",
"endtime": "15:14:54.000",
"name": "Breakfast"
},
{
"starttime": "15:16:35.000",
"endtime": "15:16:56.000",
"name": "Swimming"
},
{
"starttime": "15:15:41.000",
"endtime": "15:16:07.000",
"name": "Lunch"
},
{
"starttime": "15:10:50.000",
"endtime": "15:11:19.000",
"name": "Swimming"
},
{
"starttime": "15:17:01.000",
"endtime": "15:17:30.000",
"name": "Dinner"
}
]
},
{
"starttime": "15:18:43.000",
"endtime": "15:27:34.000",
"name": "island2",
"program": [
{
"starttime": "15:20:53.000",
"endtime": "15:21:15.000",
"name": "Yoga"
},
{
"starttime": "15:20:17.000",
"endtime": "15:20:43.000",
"name": "Breakfast"
},
{
"starttime": "15:20:28.000",
"endtime": "15:20:55.000",
"name": "Swimming"
},
{
"starttime": "15:23:23.000",
"endtime": "15:23:46.000",
"name": "Swimming"
},
{
"starttime": "15:20:24.000",
"endtime": "15:20:45.000",
"name": "Dinner"
},
{
"starttime": "15:26:17.000",
"endtime": "15:26:38.000",
"name": "Clubbing"
},
{
"starttime": "15:20:04.000",
"endtime": "15:20:28.000",
"name": "Sleeping"
}
]
}
]
}
}
How can I parse it in Java with Gson? I tried something like that but I received com.example.Model#43556938
null
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("myjsonfile.json")) {
Mapping mapping = gson.fromJson(reader, Mapping.class);
Trip trip = gson.fromJson(reader, Trip.class);
System.out.println(mapping);
System.out.println(trip);
} catch (IOException e) {
e.printStackTrace();
}
}
I want to read all the information (JSON objects and arrays). Can I do it from line to line or any suggestions?

You are fetching the Mapping object and priting the same object
Do it like this:
private static final Type REVIEW_TYPE = new TypeToken<List<Mapping>>() {
}.getType();
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(YOUR_JSON_FILE));
List<Mapping> data = gson.fromJson(reader, REVIEW_TYPE); // contains the whole mapping list
data.toScreen(); // print some value of data through iteration

When you are reading from Gson assign it to Hashmap and then read it from map. Hope This will help you
Below is the code to do it:
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.List;
import com.google.gson.Gson;
public class JsontoObj {
public static void main(String[] args) {
Gson gson = new Gson();
try (Reader reader = new FileReader("/Documents/sample.json")) {
HashMap<String, Mapping> mappings= gson.fromJson(reader, HashMap.class);
//System.out.println(mappings);
}catch (IOException e) {
e.printStackTrace();
}
}
}
class Mapping{
List<Trip> trips;
public List<Trip> getTrips() {
return trips;
}
public void setTrips(List<Trip> trips) {
this.trips = trips;
}
}
class Trip{
private String startTime;
private String endTime;
private String name;
private Program program[] = new Program[5];
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Program[] getProgram() {
return program;
}
public void setProgram(Program[] program) {
this.program = program;
}
}
class Program{
private String startTime;
private String endTime;
private String name;
public String getStartTime() {
return startTime;
}
public void setStartTime(String startTime) {
this.startTime = startTime;
}
public String getEndTime() {
return endTime;
}
public void setEndTime(String endTime) {
this.endTime = endTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Related

Parsing JSON in Java returns empty result

I am trying to parse a JSON with Java and I do not get the expected result.
Example json:
"productId": "NDAtOS0wLS0=",
"branchId": 5,
"branchCustomers":[
{"branchId":615,"customerNumber":4918,"products":[]},
{"branchId":615,"customerNumber":9753,"products":[]},
{"branchId":615,"customerNumber":9761,"products":[]}
],
"customerNumber": 240,
"subAccountNumber": 0,
"productType": 9,
"openingDate": "2016-10-02",
"values": [
{
"key": "accountingMethod",
"value": "1"
},
{
"key": "accountType",
"value": "1"
},
{
"key": "assetCashAccountId-branchId",
"value": "615"
},
{
"key": "assetCashAccountId-customerNumber",
"value": "4041240"
},
{
"key": "assetCashAccountId-subAccountNumber",
"value": "2"
},
{
"key": "assetMarginAccountId-branchId",
"value": "615"
},
{
"key": "assetMarginAccountId-customerNumber",
"value": "4041240"
},
{
"key": "assetMarginAccountId-subAccountNumber",
"value": "2"
},
{
"key": "blockingAmount",
"value": "1000000"
},
{
"key": "collateral",
"value": "C"
},
{
"key": "collateralBlockingType",
"value": "1"
},
{
"key": "executingSecurityAccountId-branchId",
"value": "615"
},
{
"key": "executingSecurityAccountId-customerNumber",
"value": "4041240"
},
{
"key": "executingSecurityAccountId-subAccountNumber",
"value": "0"
},
{
"key": "limit",
"value": "1000000"
},
{
"key": "marginAccountId-branchId",
"value": "0"
},
{
"key": "marginAccountId-customerNumber",
"value": "0"
},
{
"key": "marginAccountId-subAccountNumber",
"value": "0"
},
{
"key": "marginMarkup",
"value": "100"
},
{
"key": "rolfNolanLedger",
"value": "B01429"
},
{
"key": "settlementMethod",
"value": "1"
}
]
}
]
}],
"instances": []
}
Not all the JSONs have this structure, some may miss some of the fields. I created some DTO classes for parsing it. This is my code:
public class Response {
private String partnerId;
private byte branchId;
private long customerNumber;
private Long subAccountNumber;
private Byte productType;
private String openingDate;
private String closingDate;
private List<Values> values;
private List<Instances> instances;
private List<BranchCustomers> branchCustomers;
public String getProductid() {
return partnerId;
}
public void setProductid(String productid) {
this.partnerId = productid;
}
public byte getBranchid() {
return branchId;
}
public void setBranchid(byte branchid) {
this.branchId = branchid;
}
public long getCustomernumber() {
return customerNumber;
}
public void setCustomernumber(long customernumber) {
this.customerNumber = customernumber;
}
public Long getSubaccountnumber() {
return subAccountNumber;
}
public void setSubaccountnumber(Long subAccountNumber) {
this.subAccountNumber = subAccountNumber;
}
public Byte getProducttype() {
return productType;
}
public void setProducttype(Byte productType) {
this.productType = productType;
}
public String getOpeningdate() {
return openingDate;
}
public void setOpeningdate(String openingDate) {
this.openingDate = openingDate;
}
public String getClosingdate() {
return closingDate;
}
public void setClosingdate(String closingDate) {
this.closingDate = closingDate;
}
public List<Values> getValues() {
return values;
}
public void setValues(List<Values> values) {
this.values = values;
}
public List<Instances> getInstances() {
return instances;
}
public void setInstances(List<Instances> instances) {
this.instances = instances;
}
public List<BranchCustomers> getBranchCustomers() {
return branchCustomers;
}
public void setBranchCustomers(List<BranchCustomers> branchCustomers) {
this.branchCustomers = branchCustomers;
}
}
public class BranchCustomers {
private byte branchId;
private long customerNumber;
private List<Products> products;
public byte getBranchid() {
return branchId;
}
public void setBranchid(byte branchId) {
this.branchId = branchId;
}
public long getCustomernumber() {
return customerNumber;
}
public void setCustomernumber(long customerNumber) {
this.customerNumber = customerNumber;
}
public List<Products> getProducts() {
return products;
}
public void setProducts(List<Products> products) {
this.products = products;
}
}
public void parseJson(String response) {
try{
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Response result = mapper.readValue(response, Response.class);
System.out.println(result);
} catch (JsonMappingException e) {
e.printStackTrace
} catch (JsonProcessingException e) {
e.printStackTrace();
}
The other DTO classes "Values", "Instances" and "Products" are empty at this moment, but I do not need them yet. The problem is that the "result" value has the right structure and the right fields, but they are null or 0, depending on their data type and I cannot see what I have done wrong.
Can anyone help me?
Your getters, setters have incorrect names.
As an example, in your Response object, you have getProductid, getBranchid, and getCustomernumber with similar setter methods. Your JSON however has productId, branchId, and customerNumber. They differ as you didn't use the correct capitalization. You should use camelCase, which would turn your naming to getProductId, getBranchId, and getCustomerNumber. This then matches the JSON and it will map accordingly.
This:
public class Response {
private String partnerId;
private byte branchId;
private long customerNumber;
private Long subAccountNumber;
private Byte productType;
private String openingDate;
private String closingDate;
private List<BranchCustomers> branchCustomers;
public String getProductId() {
return partnerId;
}
public void setProductId(String productid) {
this.partnerId = productid;
}
public byte getBranchId() {
return branchId;
}
public void setBranchId(byte branchid) {
this.branchId = branchid;
}
public long getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(long customernumber) {
this.customerNumber = customernumber;
}
...
Leads to:
Response{productId='NDAtOS0wLS0=', branchId=5, customerNumber=240 ...
As a sidenote, I suggest either auto-generating the boilerplate code with your IDE or look into Project Lombok which can generate the boilerplate code by just adding an annotation. This also stops you from making naming mistakes.
Also, try and get a toString method for each pojo, as it will help you during logging or debugging.

Android Retrofit Error "Expected BEGIN_ARRAY but was BEGIN_OBJECT"

I am trying to retrieve a product list in JSON format using Retrofit. But keep getting this error. Looked at all other solutions but didn't help.
"java.lang.IllegalStateException: Expected BEGIN_ARRAY but was
BEGIN_OBJECT at line 1 column 2 path $"
I have annotations on my model class for Room database and also implements Parcelable passing as argument to other fragments.
UPDATE:
I changed the API as below. It works now.
Here is updated JSON:
[
{
"ProductComment": {
"001": {
"comment": "A comment",
"email": "tr...#yahoo.com",
"generatedProductID": "1111"
}
},
"generatedProductID": "1111",
"photoUrls": ["https://...", "https://123", "https://333"],
"title": "title",
"description": "product desc"
},
{
"ProductComment": {
"001": {
"comment": "A comment",
"email": "bm...#yahoo.com",
"generatedProductID": "2222"
},
"002": {
"comment": "A Comment",
"email": "xy...#yahoo.com",
"generatedProductID": "2222"
}
},
"generatedProductID": "2222",
"photoUrls": [ "https://...", "https://123", "https://333"],
"title": "title",
"description": "product desc"
}
]
[Before UPDATE]
my JSON is formatted like this:
{
"00001": {
"ProductComment": {
"001": {
"comment": "A comment",
"email": "tr...#yahoo.com",
"generatedProductID": "1111"
}
},
"generatedProductID": "1111",
"photoUrls": ["https://...", "https://123", "https://333"],
"title": "title",
"description": "product desc"
},
"00002": {
"ProductComment": {
"001": {
"comment": "A comment",
"email": "bm...#yahoo.com",
"generatedProductID": "2222"
},
"002": {
"comment": "A Comment",
"email": "xy...#yahoo.com",
"generatedProductID": "2222"
}
},
"generatedProductID": "2222",
"photoUrls": [ "https://...", "https://123", "https://333"],
"title": "title",
"description": "product desc"
}
}
My Product class is:
#Entity(tableName = "product")
public class Product implements Parcelable {
#PrimaryKey
#NonNull
private String generatedProductID;
private String title;
private String description;
private List<String> photoUrls;
#TypeConverters(ProductTypeConverters.class)
private List<ProductComment> comments;
public Product() {
}
protected Product(Parcel in) {
generatedProductID = in.readString();
title = in.readString();
description = in.readString();
photoUrls = in.createStringArrayList();
comments = in.createTypedArrayList(ProductComment.CREATOR);
}
public static final Creator<Product> CREATOR = new Creator<Product>() {
#Override
public Product createFromParcel(Parcel in) {
return new Product(in);
}
#Override
public Product[] newArray(int size) {
return new Product[size];
}
};
#NonNull
public String getGeneratedProductID() {
return generatedProductID;
}
public void setGeneratedProductID(#NonNull String generatedProductID) {
this.generatedProductID = generatedProductID;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
public List<ProductComment> getComments() {
return comments;
}
public void setComments(List<ProductComment> comments) {
this.comments = comments;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(generatedProductID);
dest.writeString(title);
dest.writeString(description);
dest.writeStringList(photoUrls);
dest.writeTypedList(comments);
}
}
Interface:
public interface JsonRetroService {
#GET("products.json") // relative URL at the end of github url.
Call<List<Product>> getRemoteProducts();
}
And finally in my Fragment:
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(PRODUCT_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
JsonRetroService service = retrofit.create(JsonRetroService.class);
Call<List<Product>> call = service.getRemoteProducts();
call.enqueue(new Callback<List<Product>>() {
#Override
public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {
// First check if the response is not successful. if it' ok continue.
if (!response.isSuccessful()) {
Toast.makeText(getActivity(), "Not OK: " + response.code(), Toast.LENGTH_LONG).show();
return;
}
List<Product> products = response.body();
}
#Override
public void onFailure(Call<List<Product>> call, Throwable t) {
Toast.makeText(getActivity(), "Retrofit Failure..", Toast.LENGTH_LONG).show();
Log.e(TAG, "onFailure: " , t);
}
});

Convert JSON to POJO retrofit2

How can I describe the POJO for such an answer so that the retrofit understands it? the response comes in this form. I cut it, in order to see the structure of JSON. nested objects I converted to POJO. I want to learn how to convert the main object?
[
[
"all_areas",
{
"6": {
"id": "6",
"parent_id": "0",
"left_key": "1",
"right_key": "6594",
"level": "1",
"title": "Вся Россия",
"alias": "vsya_rossiya",
"sort": "1",
"navigatorListItems": []
},
"7": {
"id": "7",
"parent_id": "6",
"left_key": "2",
"right_key": "31",
"level": "2",
"title": "Адыгея респ.",
"alias": "adygeya_resp",
"sort": "1",
"navigatorListItems": []
}
}
],
[
"current_rubrics",
[
{
"id": "7",
"parent_id": "6",
"left_key": "2",
"right_key": "19",
"level": "2",
"title": "Недвижимость",
"alias": "nedvizhimost",
"sort": "1"
},
{
"id": "8",
"parent_id": "6",
"left_key": "20",
"right_key": "47",
"level": "2",
"title": "Транспорт",
"alias": "transport",
"sort": "2"
}
]
]
]
I suppose this is what a Json should look like
{
"all_areas": [{
"6": {
"id": "6",
"parent_id": "0",
"left_key": "1",
"right_key": "6594",
"level": "1",
"title": "Вся Россия",
"alias": "vsya_rossiya",
"sort": "1",
"navigatorListItems": []
}
},
{
"7": {
"id": "7",
"parent_id": "6",
"left_key": "2",
"right_key": "31",
"level": "2",
"title": "Адыгея респ.",
"alias": "adygeya_resp",
"sort": "1",
"navigatorListItems": []
}
}
],
"current_rubrics": [{
"id": "7",
"parent_id": "6",
"left_key": "2",
"right_key": "19",
"level": "2",
"title": "Недвижимость",
"alias": "nedvizhimost",
"sort": "1"
},
{
"id": "8",
"parent_id": "6",
"left_key": "20",
"right_key": "47",
"level": "2",
"title": "Транспорт",
"alias": "transport",
"sort": "2"
}
]
}
Copy this and convert it to pojo using the website http://www.jsonschema2pojo.org or any another website which does the conversion for you
This will be your main model class:
public class Testing
{
private 7 7;
private 6 6;
public 7 get7 ()
{
return 7;
}
public void set7 (7 7)
{
this.7 = 7;
}
public 6 get6 ()
{
return 6;
}
public void set6 (6 6)
{
this.6 = 6;
}
#Override
public String toString()
{
return "ClassPojo [7 = "+7+", 6 = "+6+"]";
}
}
then there will be two subclasses (7.java & 6.java):
7.java
public class 7
{
private String[] navigatorListItems;
private String id;
private String left_key;
private String title;
private String sort;
private String level;
private String alias;
private String right_key;
private String parent_id;
public String[] getNavigatorListItems ()
{
return navigatorListItems;
}
public void setNavigatorListItems (String[] navigatorListItems)
{
this.navigatorListItems = navigatorListItems;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getLeft_key ()
{
return left_key;
}
public void setLeft_key (String left_key)
{
this.left_key = left_key;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getSort ()
{
return sort;
}
public void setSort (String sort)
{
this.sort = sort;
}
public String getLevel ()
{
return level;
}
public void setLevel (String level)
{
this.level = level;
}
public String getAlias ()
{
return alias;
}
public void setAlias (String alias)
{
this.alias = alias;
}
public String getRight_key ()
{
return right_key;
}
public void setRight_key (String right_key)
{
this.right_key = right_key;
}
public String getParent_id ()
{
return parent_id;
}
public void setParent_id (String parent_id)
{
this.parent_id = parent_id;
}
#Override
public String toString()
{
return "ClassPojo [navigatorListItems = "+navigatorListItems+", id = "+id+", left_key = "+left_key+", title = "+title+", sort = "+sort+", level = "+level+", alias = "+alias+", right_key = "+right_key+", parent_id = "+parent_id+"]";
}
}
6.java
public class 6
{
private String[] navigatorListItems;
private String id;
private String left_key;
private String title;
private String sort;
private String level;
private String alias;
private String right_key;
private String parent_id;
public String[] getNavigatorListItems ()
{
return navigatorListItems;
}
public void setNavigatorListItems (String[] navigatorListItems)
{
this.navigatorListItems = navigatorListItems;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public String getLeft_key ()
{
return left_key;
}
public void setLeft_key (String left_key)
{
this.left_key = left_key;
}
public String getTitle ()
{
return title;
}
public void setTitle (String title)
{
this.title = title;
}
public String getSort ()
{
return sort;
}
public void setSort (String sort)
{
this.sort = sort;
}
public String getLevel ()
{
return level;
}
public void setLevel (String level)
{
this.level = level;
}
public String getAlias ()
{
return alias;
}
public void setAlias (String alias)
{
this.alias = alias;
}
public String getRight_key ()
{
return right_key;
}
public void setRight_key (String right_key)
{
this.right_key = right_key;
}
public String getParent_id ()
{
return parent_id;
}
public void setParent_id (String parent_id)
{
this.parent_id = parent_id;
}
#Override
public String toString()
{
return "ClassPojo [navigatorListItems = "+navigatorListItems+", id = "+id+", left_key = "+left_key+", title = "+title+", sort = "+sort+", level = "+level+", alias = "+alias+", right_key = "+right_key+", parent_id = "+parent_id+"]";
}
}

Jackson UnrecognizedPropertyException thrown when it's there

I have a basic spring boot standalone executable jar using the bott 2.0.0.0 I think this is simple, but Google won't give up the answer. :) I am am using the latest stable jackson versions (2.9.4) but they ARE being managed by spring. This is a Boolean problem:
here is the JSON I am trying to turn into a Java Pojo (it is wrapped in a higher object but I don't think that's the problem. I haveing problems qith the boolean.
{
"guid": "a5182918-8d69-11e6-acb6-0a97227b08ed",
"organizationId": 1,
"region": "Tariff Picker",
"stages": [{
"nextStages": [],
"activities": [{
"nextActivities": [],
"name": "New Activity",
"suspensionReason": "",
"rules": [],
"isSuspend": false,
"sequence": 1,
"allowedRoles": [{
"userApplications": [],
"name": "submitApplication",
"organizationId": 0,
"workQueues": [],
"roleApplicationsForSystemRoleId": [],
"isPublic": 0,
"widgetRoles": [],
"userRoles": [],
"roleTariffReports": [],
"roleTypeId": 0,
"distributionListRoles": [],
"organizationRoles": [],
"publicationRoles": [],
"roleTariffDataSets": [],
"roleApplicationsForApplicationRoleId": [],
"workQueueArchives": [],
"id": 11,
"rolePrivileges": []
}],
"label": "New Activity",
"irrevocable": false,
"stageId": 0,
"id": 0,
"buttonPrompt": "Submit",
"guid": "2e195e0c-83d2-491f-b2e8-3ad1159d1d99",
"dataBlock": {
"sections": [{
"info": "",
"prompt": "",
"name": "First Section",
"sequence": 0,
"fields": [],
"gatingConditions": [],
"guid": "480d160c-c34f-4022-97b0-e8a1f28c49ae",
"id": -2
}],
"prompt": "",
"id": -1,
"name": ""
},
"autoExecute": false
}],
"name": "Tariff Selection Stage",
"sequence": 1,
"rules": [],
"completionMessage": "",
"guid": "65a73280-c587-486f-be8b-9107426f4730",
"id": 0,
"description": ""
}],
"stop": "3000-01-01",
"workflowTypeId": 2,
"isUserAction": false,
"start": "1900-01-01",
"isSandbox": false,
"gatingConditions": [],
"tariffId": 49,
"businessCalendarId": 1,
"applicationForms": [],
"id": 49,
"rules": []
}
I am getting an error saying there is not a field named "isSuspend" and as you can see it is there (line 3) and even set to false. here is my pojo:
private int id;
private String name;
private List<DataBlockObject> dataBlocks;
private int sequence;
private List<RuleObject> rules;
private List<AllowedRoleObject> allowedRoles;
private List<NextActivityObject> nextActivities;
private List<ActivityPermissionObject> activityPermissions;
private boolean autoExecute;
private boolean irrevocable;
private String label;
private String buttonPrompt;
private int stageId;
private boolean isSuspend;
private String suspensionReason;
private String guid;
private List<ActivitySubmitErrorPromptObject> activitySubmitErrorPrompts;
private int activitySubmitErrorTimeout;
private String breadcrumbClass;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DataBlockObject> getDataBlocks() {
return dataBlocks;
}
public void setDataBlocks(List<DataBlockObject> dataBlocks) {
this.dataBlocks = dataBlocks;
}
public int getSequence() {
return sequence;
}
public void setSequence(int sequence) {
this.sequence = sequence;
}
public List<RuleObject> getRules() {
return rules;
}
public void setRules(List<RuleObject> rules) {
this.rules = rules;
}
public List<AllowedRoleObject> getAllowedRoles() {
return allowedRoles;
}
public void setAllowedRoles(List<AllowedRoleObject> allowedRoles) {
this.allowedRoles = allowedRoles;
}
public List<NextActivityObject> getNextActivities() {
return nextActivities;
}
public void setNextActivities(List<NextActivityObject> nextActivities) {
this.nextActivities = nextActivities;
}
public List<ActivityPermissionObject> getActivityPermissions() {
return activityPermissions;
}
public void setActivityPermissions(List<ActivityPermissionObject> activityPermissions) {
this.activityPermissions = activityPermissions;
}
public boolean isAutoExecute() {
return autoExecute;
}
public void setAutoExecute(boolean autoExecute) {
this.autoExecute = autoExecute;
}
public boolean isIrrevocable() {
return irrevocable;
}
public void setIrrevocable(boolean irrevocable) {
this.irrevocable = irrevocable;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getButtonPrompt() {
return buttonPrompt;
}
public void setButtonPrompt(String buttonPrompt) {
this.buttonPrompt = buttonPrompt;
}
public int getStageId() {
return stageId;
}
public void setStageId(int stageId) {
this.stageId = stageId;
}
public boolean isSuspend() {
return isSuspend;
}
public void setSuspend(boolean isSuspend) {
this.isSuspend = isSuspend;
}
public String getSuspensionReason() {
return suspensionReason;
}
public void setSuspensionReason(String suspensionReason) {
this.suspensionReason = suspensionReason;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public List<ActivitySubmitErrorPromptObject> getActivitySubmitErrorPrompts() {
return activitySubmitErrorPrompts;
}
public void setActivitySubmitErrorPrompts(List<ActivitySubmitErrorPromptObject> activitySubmitErrorPrompts) {
this.activitySubmitErrorPrompts = activitySubmitErrorPrompts;
}
public int getActivitySubmitErrorTimeout() {
return activitySubmitErrorTimeout;
}
public void setActivitySubmitErrorTimeout(int activitySubmitErrorTimeout) {
this.activitySubmitErrorTimeout = activitySubmitErrorTimeout;
}
public String getBreadcrumbClass() {
return breadcrumbClass;
}
public void setBreadcrumbClass(String breadcrumbClass) {
this.breadcrumbClass = breadcrumbClass;
}
Can the problem be because of the getter and setter names for the field isSuspend? Try naming getter and setter getIsSuspend and setIsSuspend
Your POJO doesn't follow Java Beans naming convention. If you want Jackson to not look at the getters/setters, but only fields, see this: how to specify jackson to only use fields - preferably globally

Deserializing 2D JSON array to bean using GSON

I have not been able to map this nested array rows->elements to my javabean. Is gson actually capable of handling this kind of mapping? I also tried a different approach, which you can see if you look at the commented out Java code.
package scratch;
import java.util.ArrayList;
import java.util.List;
/*
{
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "897 mi",
"value" : 1443464
},
"duration" : {
"text" : "14 hours 32 mins",
"value" : 52327
},
"status" : "OK"
}
]
},
{
"elements" : [
{
"distance" : {
"text" : "378 mi",
"value" : 607670
},
"duration" : {
"text" : "6 hours 22 mins",
"value" : 22908
},
"status" : "OK"
}
]
}
]
}
*/
public class GeoZipCodesBean2 {
// private Elem[][] rows;
// public Elem[][] getRows() {
// return rows;
// }
//
// public void setRows(Elem[][] rows) {
// this.rows = rows;
// }
private List<List<Elem>>rows;
public List<List<Elem>> getRows() {
return rows;
}
public void setRows(List<List<Elem>> rows) {
this.rows = rows;
}
public static class Elem {
private Distance distance;
private Duration duration;
public Distance getDistance() {
return distance;
}
public void setDistance(Distance distance) {
this.distance = distance;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
}
public static class Distance {
private String text;
private Integer value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
public static class Duration {
private String text;
private Integer value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Integer getValue() {
return value;
}
public void setValue(Integer value) {
this.value = value;
}
}
}
GeoZipCodesBean2 geoZipCodesBean2 = new Gson().fromJson(str, GeoZipCodesBean2.class);
This should be the JSON format for your GeoZipCodesBean2 object (if rows is a List<List<Elem>>)
{
"rows": [
[
{
"elements": [
{
"distance": {
"text": "897 mi",
"value": 1443464
},
"duration": {
"text": "14 hours 32 mins",
"value": 52327
},
"status": "OK"
}
]
},
{
"elements": [
{
"distance": {
"text": "378 mi",
"value": 607670
},
"duration": {
"text": "6 hours 22 mins",
"value": 22908
},
"status": "OK"
}
]
}
]
]
}
This is the code for converting to/from json
public static void main(String[] args) {
Gson gson = new GsonBuilder().create();
GeoZipCodesBean2 geo = new GeoZipCodesBean2();
List<List<Elem>> rows = new ArrayList<List<Elem>>();
List<Elem> elem = new ArrayList<Elem>();
Elem e1 = new Elem();
Distance d = new Distance();
d.setText("fads");
d.setValue(1234);
e1.setDistance(d);
elem.add(e1);
rows.add(elem);
geo.setRows(rows);
String json = gson.toJson(geo);
//The following prints {"rows":[[{"distance":{"text":"fads","value":1234}}]]}
System.out.println(json);
json = "{\"rows\":[[{\"distance\":{\"text\":\"fads\",\"value\":1234}, \"status\":\"OK\"}]]}";
GeoZipCodesBean2 geo2 = gson.fromJson(json, GeoZipCodesBean2.class);
//The following prints 1234
System.out.println(geo2.getRows().get(0).get(0).getDistance().getValue());
}

Categories