selection of values by keys of json file using jackson - java

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}

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

How to Remove keyname from json string

I have a json string like this.
[
{
"_source": {
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"short_name": "Jam Brong"
}
},
{
"_source": {
"name": "Jam abcfdfjn",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"short_name": "Jam abcfdfjn"
}
}
]
I need to remove "_source":{
so i can get a json string like this.
[
{
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"short_name": "Jam Brong"
},
{
"name": "Jam abcfdfjn",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"short_name": "Jam abcfdfjn"
}
]
I tried to use replaceAll("("_source:{"),"");
This code will show me some error like number expected.
I don't know how to use regex for the string which contains _ and { .
Before i think to use replaceAll, i tried jackson like this.
String responses ="";
ObjectNode node = new ObjectMapper().readValue(response.toString(), ObjectNode.class);
ProductList productListInstance = new ProductList();
List<Product> productList = new ArrayList<>();
try {
if(node.get("hits").get("hits").isArray()){
for (final JsonNode objNode : node.get("hits").get("hits")) {
Product products = new ObjectMapper().readValue(objNode.get("_source").toString(), Product.class);
productList.add(products);
}
productListInstance.setProductList(productList);
}
responses = productListInstance.toString();
}
catch (Exception ex){
responses = productListInstance.toString();
}
return responses;
actually the first json string was like this :
{
"hits": {
"hits": [
{
"_source": {
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"short_name": "Jam Brong"
}
},
{
"_source": {
"name": "Jam abcfdfjn",
"image": "https://asdf.sdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"short_name": "Jam abcfdfjn"
}
}
]
}
}
You can use Jackson to achieve this. First, define a bean representing your data model.
public static class Source {
private String name;
private String image;
private String price;
private String slug;
private String shortName;
#JsonCreator
public Source(#JsonProperty("_source") Map<String, Object> rawJson) {
this.name = rawJson.get("name").toString();
this.image = rawJson.get("image").toString();
this.price = rawJson.get("price").toString();
this.slug = rawJson.get("slug").toString();
this.shortName = rawJson.get("short_name").toString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getSlug() {
return slug;
}
public void setSlug(String slug) {
this.slug = slug;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
}
Observe the #JsonCreator annotation on the constructor. Then write the code for serialization and deserialization:
final ObjectMapper mapper = new ObjectMapper();
Source[] sources = mapper.readValue(jsonStr, Source[].class);
String converted = mapper.writeValueAsString(sources);
System.out.println(converted);
Prints:
[
{
"name": "Jam Brong",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/fb7d3dcb505fba76262c0c6383d844ae.jpg",
"price": "2500",
"slug": "133-jam-brong",
"shortName": "Jam Brong"
},
{
"name": "Jam abcfdfjn",
"image": "https://asdf.asdf.com/asdf/image/upload/w_30,h_30,c_fill/product/7bbd3d081dd03c442e4cb27321a7b50c.jpg",
"price": "10888",
"slug": "87-jam-abcfdfjn",
"shortName": "Jam abcfdfjn"
}
]

Converting JSON Object to Java Object in Jersey JAX-RS

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.

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.

GSON NumberFormatException when lists are involved

I'm trying to parse the JSON from an API request into POJO objects.
The JSON data that I receive:
{
"friends": {
"user": [
{
"name": "Tomstyan",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/24514aeefa73fab11c176cbf38a331ae.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/24514aeefa73fab11c176cbf38a331ae.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/24514aeefa73fab11c176cbf38a331ae.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/24514aeefa73fab11c176cbf38a331ae.png",
"size": "extralarge"
}
],
"url": "https://www.last.fm/user/Tomstyan",
"country": "",
"age": "0",
"gender": "n",
"subscriber": "FIXME",
"playcount": "714",
"playlists": "0",
"bootstrap": "0",
"registered": {
"unixtime": "1456094418"
},
"type": "FIXME",
"scrobblesource": "FIXME"
},
{
"name": "Bigham96",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/2ca8614f31e70fcabe0678a8a622d48c.png",
"size": "extralarge"
}
],
"url": "https://www.last.fm/user/Bigham96",
"country": "",
"age": "0",
"gender": "n",
"subscriber": "FIXME",
"playcount": "16988",
"playlists": "0",
"bootstrap": "0",
"registered": {
"unixtime": "1445348751"
},
"type": "FIXME",
"scrobblesource": "FIXME"
},
{
"name": "UKJonnyMfc",
"realname": "Jonny Dring",
"image": [
{
"#text": "https://lastfm-img2.akamaized.net/i/u/34s/f600685470064369c306879e464cb470.png",
"size": "small"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/64s/f600685470064369c306879e464cb470.png",
"size": "medium"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/174s/f600685470064369c306879e464cb470.png",
"size": "large"
},
{
"#text": "https://lastfm-img2.akamaized.net/i/u/300x300/f600685470064369c306879e464cb470.png",
"size": "extralarge"
}
],
"url": "https://www.last.fm/user/UKJonnyMfc",
"country": "",
"age": "0",
"gender": "n",
"subscriber": "FIXME",
"playcount": "29056",
"playlists": "0",
"bootstrap": "0",
"registered": {
"#text": "2014-02-11 22:38:27",
"unixtime": "1392158307"
},
"type": "FIXME",
"scrobblesource": "FIXME"
}
],
"#attr": {
"for": "tomgreen32",
"page": "1",
"perPage": "50",
"totalPages": "1",
"total": "3"
}
}
}
And the Objects i have to put these in are as follows:
Friends
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Friends {
#SerializedName("user")
#Expose
private List<User> user = null;
#SerializedName("#attr")
#Expose
private Attr attr;
public List<User> getUser() {
return user;
}
public void setUser(List<User> user) {
this.user = user;
}
public Attr getAttr() {
return attr;
}
public void setAttr(Attr attr) {
this.attr = attr;
}
}
Attr
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Attr {
#SerializedName("for")
#Expose
private String _for;
#SerializedName("page")
#Expose
private String page;
#SerializedName("perPage")
#Expose
private String perPage;
#SerializedName("totalPages")
#Expose
private String totalPages;
#SerializedName("total")
#Expose
private String total;
public String getFor() {
return _for;
}
public void setFor(String _for) {
this._for = _for;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getPerPage() {
return perPage;
}
public void setPerPage(String perPage) {
this.perPage = perPage;
}
public String getTotalPages() {
return totalPages;
}
public void setTotalPages(String totalPages) {
this.totalPages = totalPages;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
}
Image
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Image {
#SerializedName("#text")
#Expose
private String text;
#SerializedName("size")
#Expose
private String size;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
}
Registered
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Registered {
#SerializedName("#text")
#Expose
private String text;
#SerializedName("unixtime")
#Expose
private String unixtime;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getUnixtime() {
return unixtime;
}
public void setUnixtime(String unixtime) {
this.unixtime = unixtime;
}
}
Main
In my main class i have the following code to parse the JSON.
final URL reqURL = new URL("http://ws.audioscrobbler.com/2.0/?method=user.getfriends&" +
"user=" + username +
"&api_key=" + API_KEY +
"&format=json");
final InputStream inputstream = APISend(reqURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputstream));
GetFriends getfriends = gson.fromJson(reader, GetFriends.class);
System.out.println(getfriends.getFriends().getUser().get(0).getName());
From what I've read, the list of users might be causing an issue, I've read about TypeToken but i cant figure out how to implement it. This is the first time I've tried to do anything with gson so any help would be appriceted. Thanks.
UPDATE
The error in full
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.NumberFormatException: For input string: "2014-02-11 22:38:27"
at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:249)
at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:239)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:116)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:216)
at com.google.gson.Gson.fromJson(Gson.java:879)
at com.google.gson.Gson.fromJson(Gson.java:817)
at Main.getUserFriends(Main.java:66)
at Main.main(Main.java:89)
Caused by: java.lang.NumberFormatException: For input string: "2014-02-11 22:38:27"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at sun.misc.FloatingDecimal.parseDouble(Unknown Source)
at java.lang.Double.parseDouble(Unknown Source)
at com.google.gson.stream.JsonReader.nextInt(JsonReader.java:1198)
at com.google.gson.internal.bind.TypeAdapters$11.read(TypeAdapters.java:247)
... 16 more
UPDATE 2
GetFriends method was created when i used http://www.jsonschema2pojo.org/ to generate the pojo's
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class GetFriends {
#SerializedName("friends")
#Expose
private Friends friends;
public Friends getFriends() {
return friends;
}
public void setFriends(Friends friends) {
this.friends = friends;
}
}

Categories

Resources