Converting JSON Object to Java Object in Jersey JAX-RS - java

I'm trying to convert a json object to an java object in a rest api but I don't know how to create my java bean.
The json object itself contains multiple objects and arrays. What instance variable do i have to put in the java bean to match these? My first guess would be another beans but this sounds somewhat messy with a high nesting extent.
Here is a sample json for visualization:
{
key1: value,
key2: value,
anotherJsonObject: {
key3: value,
key4: value,
anotherJsonObject: {
key5: value
...
},
anotherJsonArray: [
{
key6: value,
key7: value
},
{
key6: value,
key7: value
}
]
}
}

Here is the complete example using JAX-RS
So first let us define sample JSON.
[{
"id": 1,
"firstName": "Jeanette",
"lastNname": "Penddreth",
"email": "jpenddreth0#census.gov",
"gender": "Female",
"ipAddress": "26.58.193.2",
"websitesVisited": [{
"websiteName": "www.youtube.com",
"IpAddress": "26.58.193.6",
"timeSpent": "1 Hr",
"NoOfTimeVisitedInDay": "10"
},
{
"websiteName": "www.facebook.com",
"IpAddress": "26.58.193.10",
"timeSpent": "2 Hr",
"NoOfTimeVisitedInDay": "20"
}
]
}
, {
"id": 2,
"firstName": "Giavani",
"lastName": "Frediani",
"email": "gfrediani1#senate.gov",
"gender": "Male",
"ipAddress": "229.179.4.212",
"websitesVisited": [{
"websiteName": "www.youtube.com",
"IpAddress": "26.58.193.6",
"timeSpent": "1 Hr",
"NoOfTimeVisitedInDay": "10"
},
{
"websiteName": "www.facebook.com",
"IpAddress": "26.58.193.10",
"timeSpent": "2 Hr",
"NoOfTimeVisitedInDay": "20"
}
]
}, {
"id": 3,
"firstName": "Noell",
"lastName": "Bea",
"email": "nbea2#imageshack.us",
"gender": "Female",
"ipAddress": "180.66.162.255",
"websitesVisited": [{
"websiteName": "www.youtube.com",
"IpAddress": "26.58.193.6",
"timeSpent": "1 Hr",
"NoOfTimeVisitedInDay": "10"
},
{
"websiteName": "www.facebook.com",
"IpAddress": "26.58.193.10",
"timeSpent": "2 Hr",
"NoOfTimeVisitedInDay": "20"
}
]
}, {
"id": 4,
"firstName": "Willard",
"lastName": "Valek",
"email": "wvalek3#vk.com",
"gender": "Male",
"ipAddress": "67.76.188.26",
"websitesVisited": [{
"websiteName": "www.youtube.com",
"IpAddress": "26.58.193.6",
"timeSpent": "1 Hr",
"NoOfTimeVisitedInDay": "10"
},
{
"websiteName": "www.facebook.com",
"IpAddress": "26.58.193.10",
"timeSpent": "2 Hr",
"NoOfTimeVisitedInDay": "20"
}
]
}
]
Now let us define POJO(Plain OLD JAVA OBJECT)
As we can see our sample JSON has array of Students Object and student Object has some properties like id, firstName,lastName,email,gender,ipAddress and another List of Object called websitesVisited.
websitesVisited has some more properties like websiteName,IpAddress,timeSpent,NoOfTimeVisitedInDay
Now let us define POJO
First define inner OBJECT called Website.
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Websites {
String websiteName;
String ipAddress;
String timeSpent;
String NoOfTimeVisitedInDay;
public Websites() {
}
public String getWebsiteName() {
return websiteName;
}
public void setWebsiteName(String websiteName) {
this.websiteName = websiteName;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getTimeSpent() {
return timeSpent;
}
public void setTimeSpent(String timeSpent) {
this.timeSpent = timeSpent;
}
public String getNoOfTimeVisitedInDay() {
return NoOfTimeVisitedInDay;
}
public void setNoOfTimeVisitedInDay(String noOfTimeVisitedInDay) {
NoOfTimeVisitedInDay = noOfTimeVisitedInDay;
}
#Override
public String toString() {
return "Websites [websiteName=" + websiteName + ", ipAddress=" + ipAddress + ", timeSpent=" + timeSpent +
", NoOfTimeVisitedInDay=" + NoOfTimeVisitedInDay + "]";
}
}
Now lets define the main object Students
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement
public class Students {
String id;
String firstName;
String lastName;
String email;
String gender;
String ipAddress;
List < Websites > websitesVisited;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public List < Websites > getWebsitesVisited() {
return websitesVisited;
}
public void setWebsitesVisited(List < Websites > websitesVisited) {
this.websitesVisited = websitesVisited;
}
#Override
public String toString() {
return "Students [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email +
", gender=" + gender + ", ipAddress=" + ipAddress + ", websitesVisited=" + websitesVisited + "]";
}
}
If you notice students Object has properties called List websitesVisited.
Now write post method
#POST
#Consumes({
MediaType.APPLICATION_JSON
})
#Produces({
MediaType.APPLICATION_JSON
})
#Path("JsonPostExample")
public String JsonPostExample(#PathParam("studentId") String studentId, List < Students > studentS) {
System.out.println(studentS.toString());
// Do whatever you want to do with the object
return studentId;
}
I hope it helps.

Related

java/ jackson question, Need to parse a JSON to a list of type Employee (currently using jackson) using logic check

Trying to read in a Employee JSON and parse it to a list of type Employee but I need to check if the firstname and lastname contain only alpha and the dob is in format MM/DD/YYYY. If not then don't create the Employee object. I am currently using jackson and am able to parse the json and create the list of type Employee but I'm not sure how to implement the logic to check for alpha and the date format.
Below is my code:
Employee JSON
[
{
"firstname": "John",
"lastname": "Doe",
"dob": "12/25/1999"
},
{
"firstname": "Bob",
"lastname": "Adams",
"dob": "04/12/1970"
},
{
"firstname": "Jane",
"lastname": "Chan",
"dob": "05/05/1955"
},
{
"firstname": "Jack",
"lastname": "Smith",
"dob": "06/24/1967"
},
{
"firstname": "Ken",
"lastname": "Green",
"dob": "02/11/1978"
},
{
"firstname": "Jake",
"lastname": "Peralta",
"dob": "09/24/1989"
},
{
"firstname": "Kevin",
"lastname": "Jones",
"dob": "03/12/1992"
},
{
"firstname": "Bruce",
"lastname": "Powers",
"dob": "06/22/1994"
}
]
Employee class
public class Employee {
private String firstname;
private String lastname;
private String dob;
public Employee() {
}
public Employee(String firstName, String lastName, String dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
#Override
public String toString() {
return "Employee [firstName=" + firstname + ", lastName=" + lastname + ", dob=" + dob + "]";
}
}
Parsing json to employee list
private List<Employee> readEmpolyeeJson() {
List<Employee> empList = new ArrayList<>();
if(inputJsonLocation != null || !inputJsonLocation.trim().isEmpty()) { //json location is not empty
//read json
ObjectMapper objectMapper = new ObjectMapper();
try {
empList = objectMapper.readValue(new File(inputJsonLocation), new TypeReference<List<Employee>>(){});
}
catch (JsonParseException e) {
e.printStackTrace();
}
catch (JsonMappingException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("empList length: "+empList.size());
for(int i=0; i<empList.size(); i++)
System.out.println(empList.get(i).getFirstname()+", "+empList.get(i).getLastname()+", "+empList.get(i).getDob());
}
return empList;
}

selection of values by keys of json file using jackson

This is possibly the dumbest question on the entire site. I am new to Java and JSON and I need help. I am using API Jackson. The program receives a JSON file. From it I need to get:
List of people between the ages of 20 and 30, sorted by name
Unique list of cities;
The number of people with an age interval of 0-10, 11-20, 21-30 and so on.
At the moment I have learned how to translate a json file into a List java
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
try {
List<Data> data = Arrays.asList(mapper.readValue(Paths.get("C:\\data.json").toFile(), Data[].class));
System.out.println(data);
} catch (JsonParseException jsonParseException) {
jsonParseException.printStackTrace();
} catch (JsonMappingException jsonMappingException) {
jsonMappingException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
A class was created to read the json file
public class Data {
private int id;
private String firstName;
private String lastName;
private String dateOfBirth;
private String city;
public Data(int id, String firstName, String lastName, String dateOfBirth, String city) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.city = city;
}
public Data() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
return "[id = " + id + ", firstName = " + firstName + ", lastName = " + lastName + ", dateOfBirth = " + dateOfBirth + ", city = " + city + "]";
}
}
Json file looks like this
[
{
"id": "1",
"firstName": "Lesley",
"lastName": "Bryan",
"dateOfBirth": "11/28/61",
"city": "Southampton–Portsmouth"
},
{
"id": "2",
"firstName": "Edward",
"lastName": "Houston",
"dateOfBirth": "10/5/92",
"city": "Southampton–Portsmouth"
},
{
"id": "3",
"firstName": "Donald",
"lastName": "Ross",
"dateOfBirth": "12/10/79",
"city": "Glasgow"
},
{
"id": "4",
"firstName": "Peter",
"lastName": "Kelly",
"dateOfBirth": "3/17/04",
"city": "Birmingham–Wolverhampton"
},
{
"id": "5",
"firstName": "Anthony",
"lastName": "McKinney",
"dateOfBirth": "3/6/68",
"city": "Liverpool"
},
{
"id": "6",
"firstName": "David",
"lastName": "Stewart",
"dateOfBirth": "4/11/73",
"city": "Leeds–Bradford"
},
{
"id": "7",
"firstName": "Christopher",
"lastName": "Austin",
"dateOfBirth": "12/28/74",
"city": "Birmingham–Wolverhampton"
},
{
"id": "8",
"firstName": "Alvin",
"lastName": "Hodge",
"dateOfBirth": "11/25/58",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "9",
"firstName": "Gerald",
"lastName": "Higgins",
"dateOfBirth": "6/28/55",
"city": "Liverpool"
},
{
"id": "10",
"firstName": "Amos",
"lastName": "Owens",
"dateOfBirth": "1/16/01",
"city": "Manchester-Salford"
},
{
"id": "11",
"firstName": "Christian",
"lastName": "Bishop",
"dateOfBirth": "11/14/50",
"city": "Nottingham"
},
{
"id": "12",
"firstName": "Robert",
"lastName": "Caldwell",
"dateOfBirth": "12/8/80",
"city": "Manchester-Salford"
},
{
"id": "13",
"firstName": "Brian",
"lastName": "Heath",
"dateOfBirth": "9/23/02",
"city": "Newcastle upon Tyne–Sunderland"
},
{
"id": "14",
"firstName": "Mark",
"lastName": "Anthony",
"dateOfBirth": "1/8/92",
"city": "London"
},
{
"id": "15",
"firstName": "Mark",
"lastName": "Watson",
"dateOfBirth": "7/27/91",
"city": "Nottingham"
},
{
"id": "16",
"firstName": "Charles",
"lastName": "Stafford",
"dateOfBirth": "1/26/90",
"city": "Birmingham–Wolverhampton"
},
{
"id": "17",
"firstName": "Steven",
"lastName": "Merritt",
"dateOfBirth": "12/4/63",
"city": "Leeds–Bradford"
},
{
"id": "18",
"firstName": "John",
"lastName": "Holmes",
"dateOfBirth": "4/22/52",
"city": "Southampton–Portsmouth"
},
{
"id": "19",
"firstName": "Mervin",
"lastName": "Lewis",
"dateOfBirth": "10/27/95",
"city": "Birmingham–Wolverhampton"
},
{
"id": "20",
"firstName": "Peter",
"lastName": "Marsh",
"dateOfBirth": "12/10/63",
"city": "Glasgow"
},
{
"id": "21",
"firstName": "Piers",
"lastName": "Harrington",
"dateOfBirth": "4/27/85",
"city": "London"
},
{
"id": "22",
"firstName": "Matthew",
"lastName": "O’Brien’",
"dateOfBirth": "1/19/59",
"city": "Manchester-Salford"
}
]
Please tell me in what sequence of actions to complete the task. Once again I apologize for such a stupid message.
P.S.: All names, surnames and dates from the json file were obtained at random.
First, you need to update Data class to facilitate handling of ages and age groups:
Change type of dateOfBirth to LocalDate, update constructor/getter/provide custom setter to handle dates in the 20-th century
Add methods to get age in years and age group as String:
Update toString to print age
class Data {
// ...
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "M/d/yy")
private LocalDate dateOfBirth;
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dob) {
if (dob.isAfter(LocalDate.now())) {
dob = dob.minusYears(100);
}
this.dateOfBirth = dob;
}
#JsonIgnore
public int getAge() {
return Period.between(dateOfBirth, LocalDate.now()).getYears();
}
#JsonIgnore
public String getAgeGroup() {
int age = getAge();
if (age < 11) {
return "0..10";
}
return (age/10*10+1) + ".." + ((age/10 + 1) * 10);
}
#Override
public String toString() {
return "[id = " + id + ", age=" + getAge() + ", firstName = " + firstName + ", lastName = " + lastName + ", dateOfBirth = " + dateOfBirth + ", city = " + city + "]";
}
}
Then you can get required subsets of data from the input list:
// get people aged from 20 to 30 sorted by last name/first name
List<Data> age20to30 = data
.stream()
.filter(p -> p.getAge() >= 20 && p.getAge() < 30)
.sorted(Comparator.comparing(p -> p.getLastName() + " " + p.getFirstName()))
.collect(Collectors.toList());
age20to30.forEach(System.out::println);
// get sorted list of unique cities (using TreeSet as a SortedSet)
Set<String> cities = data
.stream()
.map(Data::getCity)
.collect(Collectors.toCollection(TreeSet::new));
cities.forEach(System.out::println);
// get stats by age groups
Map<String, Long> byAges = data
.stream()
.collect(Collectors.groupingBy(Data::getAgeGroup, TreeMap::new, Collectors.counting()));
System.out.println(byAges);
Output
[id = 14, age=28, firstName = Mark, lastName = Anthony, dateOfBirth = 1992-01-08, city = London]
[id = 2, age=27, firstName = Edward, lastName = Houston, dateOfBirth = 1992-10-05, city = Southampton–Portsmouth]
[id = 19, age=24, firstName = Mervin, lastName = Lewis, dateOfBirth = 1995-10-27, city = Birmingham–Wolverhampton]
[id = 15, age=29, firstName = Mark, lastName = Watson, dateOfBirth = 1991-07-27, city = Nottingham]
Birmingham–Wolverhampton
Glasgow
Leeds–Bradford
Liverpool
London
Manchester-Salford
Newcastle upon Tyne–Sunderland
Nottingham
Southampton–Portsmouth
{11..20=3, 21..30=4, 31..40=3, 41..50=3, 51..60=4, 61..70=5}

Jackson obectMapperwriteValue() not working as expected

I deserialize the data.json file to Customer.java. And tried to serialize Customer.java to shopping.json. But it is showing two list objects (list and food) in the serialized json data. There should be only one list (i.e., food). What went wrong? Please see the code below:
ShoppingList.java
private String name;
private int amount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
#Override
public String toString() {
return "ShoppingList [name=" + name + ", amount=" + amount + "]";
}
Customer.java
private String date;
private String name;
private String store;
#JsonProperty("food")
private List<ShoppingList> food;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStore() {
return store;
}
public void setStore(String store) {
this.store = store;
}
public List<ShoppingList> getList() {
return food;
}
public void setList(List<ShoppingList> list) {
this.food = list;
}
#Override
public String toString() {
return "Customer [date=" + date + ", name=" + name + ", store=" + store + ", food=" + food + "]";
}
Test.java
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
File file = new File("data.json");
ObjectMapper mapper = new ObjectMapper();
Customer m = mapper.readValue(file, Customer.class);
System.out.println(m.toString());
System.out.println(m.getList().toString());
mapper.writeValue(new File("shopping.json"), m);
}
data.json
{
"date": "2016-07-14",
"name": "Candice",
"store": "aStore",
"food": [
{
"name": "eggs",
"amount": 6
},
{
"name": "Chicken",
"amount": 1
},
{
"name": "Bananas",
"amount": 5
},
{
"name": "Pasta",
"amount": 1
}
]
}
shopping.json
{
"date": "2016-07-14",
"name": "Candice",
"store": "aStore",
"list": [ //This list is generated extra.
{
"name": "eggs",
"amount": 6
},
{
"name": "Chicken",
"amount": 1
},
{
"name": "Bananas",
"amount": 5
},
{
"name": "Pasta",
"amount": 1
}
],
"food": [
{
"name": "eggs",
"amount": 6
},
{
"name": "Chicken",
"amount": 1
},
{
"name": "Bananas",
"amount": 5
},
{
"name": "Pasta",
"amount": 1
}
]
}
I tried in different ways but no luck.
Thanks in advance.
This might be caused for your naming. Rename you getList method and setList method to getFood and setFood and try again.

Android Retrofit POJO model

Hi i'm trying to learn android and now implementing the retrofit 1.9 for my rest POST and GET request can somebody help me on how to model given json objects and strings? im very confused on some tutorials I have learned how make a pojo for this json object
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
}}]}
Using this model
Contacts.class
public class Contacts {
#SerializedName("contacts")
#Expose
private List<Contact> contacts = new ArrayList<Contact>();
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
and Contact.class for the objects
public class Contact {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("address")
#Expose
private String address;
#SerializedName("gender")
#Expose
private String gender;
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getEmail() {return email;}
public void setEmail(String email) {this.email = email;}
public String getAddress() {return address;}
public void setAddress(String address) {this.address = address;}
public String getGender() {return gender;}
public void setGender(String gender) {this.gender = gender;}}
And Calling the list using this on my MainActivity.class
private void getContacts() {
final ProgressDialog loading = ProgressDialog.show(this, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
api.getContacts(new Callback<Contacts>() {
#Override
public void success(Contacts contacts, Response response) {
loading.dismiss();
List<Contact> contactList = contacts.getContacts();
String[] items = new String[contactList.size()];
for (int i = 0; i < contactList.size(); i++) {
items[i] = contactList.get(i).getName();
}
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.simple_list,R.id.textview, items);
//Setting adapter to listviesw
listView.setAdapter(adapter);
}
#Override
public void failure(RetrofitError error) {
}
});
}
THen my Question is how should i make a model out of this array Object?
{
"-KNea90tV5nZlkeqxc3Q": {
"accountName": "Mark Papyrus",
"accountNumber": "12435656443",
"accountType": "Peso Savings"
},
"-KNeaPmBoTXV4mQC6cia": {
"accountName": "Mark Dremeur",
"accountNumber": "12435656444",
"accountType": "Peso Checking"
}
i found it confusing how to make models and difference of given json arrays pls guide me thanks.
I think me and you are having the same problems but I am stuck so I can help you as far as I can . First you cannot use jsonschema2pojo.org to create the pojo class you need to use hashmap from what I understand "-KNea90tV5nZlkeqxc3Q": is a key but 1 of the classes should be the following ( also the accountype since its a type you can use enum but it would be bit harder to code)
public class Account {
private String accountName;
private String accountNumber;
private String accountType;
public Account() {
}
public String getAccountName() {return accountName;}
public void setAccountName(String accountName) {
this.accountName=accountName;}
// *** repeat for the accountnumber and accountype
}
if the key "KNea90tV5nZlkeqxc3Q" is dynamic and need to capture them, you musto to use a hashmap in your model to catch them correctly.
check this issue it could be useful:
Parse Dynamic Key Json String using Retrofit

gson parsing nested json objects from google matrix api

I want to do something like this posted here, but using this JSON response:
{
"status": "OK",
"origin_addresses": [ "Vancouver, BC, Canada", "Seattle, État de Washington, États-Unis" ],
"destination_addresses": [ "San Francisco, Californie, États-Unis", "Victoria, BC, Canada" ],
"rows": [ {
"elements": [ {
"status": "OK",
"duration": {
"value": 340110,
"text": "3 jours 22 heures"
},
"distance": {
"value": 1734542,
"text": "1 735 km"
}
}, {
"status": "OK",
"duration": {
"value": 24487,
"text": "6 heures 48 minutes"
},
"distance": {
"value": 129324,
"text": "129 km"
}
} ]
}, {
"elements": [ {
"status": "OK",
"duration": {
"value": 288834,
"text": "3 jours 8 heures"
},
"distance": {
"value": 1489604,
"text": "1 490 km"
}
}, {
"status": "OK",
"duration": {
"value": 14388,
"text": "4 heures 0 minutes"
},
"distance": {
"value": 135822,
"text": "136 km"
}
} ]
} ]
}
my classes are:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
class Response {
private String status;
private String[] destination_addresses;
private String[] origin_addresses;
private Elements[] rows;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String[] getDestination_addresses() {
return destination_addresses;
}
public void setDestination_addresses(String[] destination_addresses) {
this.destination_addresses = destination_addresses;
}
public String[] getOrigin_addresses() {
return origin_addresses;
}
public void setOrigin_addresses(String[] origin_addresses) {
this.origin_addresses = origin_addresses;
}
public Elements[] getRows() {
return rows;
}
public void setRows(Elements[] rows) {
this.rows = rows;
}
}
class Distance {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
class Duration {
private String text;
private String value;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
class Elements {
Duration duration[];
Distance distance[];
String status;
}
public class JSON {
public static void main(String[] args) throws IOException {
JsonReader reader = new JsonReader(new BufferedReader(new FileReader(
"json.json")));
reader.setLenient(true);
Response r = (new Gson().fromJson(reader, Response.class));
StringBuilder sb = new StringBuilder();
for (String s : r.getDestination_addresses()) {
sb.append(s);
}
System.out.println("getDestination_addresses: " + sb.toString());
StringBuilder sb1 = new StringBuilder();
for (String s : r.getOrigin_addresses()) {
sb1.append(s);
}
System.out.println("getOrigin_addresses: " + sb1.toString());
System.out.println("getStatus(): " + r.getStatus());
System.out.println("Rows length " + r.getRows().length);
System.out.println(r.getRows()[0].status); // here i get null
}
}
But it does not work fully, I can get only this fields correctly:
private String status;
private String[] destination_addresses;
private String[] origin_addresses;
the are information is null.
Your declarations are wrong. Change Response into
class Response {
private String status;
private String[] destination_addresses;
private String[] origin_addresses;
private Item[] rows;
...
}
where Item is:
class Item {
private Element[] elements;
...
}
and Element is:
class Element{
Duration duration;
Distance distance;
String status;
...
}
This should solve. Three more tips for you:
We are in full generics era, so avoid Element[] and use List instead (and so on, anycase I kept you "style" in answer)
Use something like this to visualize your JSON, it will help you to understand its structure
Duration and Distance have the same structure, maybe you can save a declaration, Gson does not care about name of classes, it looks at structure of it. From Gson point of view, Duration and Distance are the same: a string plus an integer.

Categories

Resources