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.
Related
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"
}
]
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.
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;
}
}
Here is a json file.
{
"RackItems": [
{
"Name": "Profile",
"Description": "Profile Items",
"MainContentItems": [
{
"Name": "Personal",
"Description": "Profile",
"ContentItems": [
{
"Name": "Personal Details",
"Type": "Profile"
}
]
},
{
"Name": "My Playlists",
"Description": "Playlists",
"ContentItems": [
{
"Name": "My Playlists",
"Description": "My Playlists",
"Type": "Playlist"
}
]
}
]
},
{
"Name": "Home",
"Description": "Home Items",
"ContentItems": [
{
"Name": "Top Songs",
"Description": "Top Songs",
"Type": "Song"
},
{
"Name": "Top Albums",
"Description": "Top Albums",
"Type": "Album"
}
]
}
],
"DetailedItems": {
"Genre": {
"Name": "Genre",
"Description": "Genre Items",
"ContentItems": [
{
"Name": "Top ## Songs",
"Description": "Top Songs"
},
{
"Name": "Top ## Albums",
"Description": "Top Albums"
}
]
},
"UserProfile": {
"Name": "User Profile",
"Description": "User Profile",
"MainContentItems": [
{
"Name": "Personal",
"Description": "Profile",
"ContentItems": [
{
"Name": "Personal Details",
"Description": "Personal Details",
"ItemType": "ProfileView"
}
]
},
{
"Name": "Playlists",
"Description": "Playlists",
"ContentItems": [
{
"Name": "Playlists",
"Description": "Playlists",
"ItemType": "Playlist"
}
]
}
]
}
},
"DownloadSongs": {
"Name": "Download Songs",
"Description": "Download Songs",
"ItemType": "DownloadSongsResult"
}
}
And here are individual pojo class:
#JsonIgnoreProperties(ignoreUnknown = true)
public class ContentMusicPlayerChild {
String Name, Description;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
and other pojo with same type of getter setter with top class
List<Object> cStringList = new ArrayList<>();
#JsonAnyGetter
public List<Object> getcStringList() {
return cStringList;
}
#JsonAnySetter
public void setcStringList(List<Object> cStringList) {
this.cStringList = cStringList;
}
Here I used JsonAnyGetter and JsonAnySetter to get any data that contains. Like
ContentMusicPlayer contentMusicPlayer = null;
ObjectMapper objectMapper = new ObjectMapper();
contentMusicPlayer = objectMapper.readValue(UtilMethod.loadJSONFromAsset(context), ContentMusicPlayer.class);
Log.e("contentMusicPlayer", contentMusicPlayer+ "");
return contentMusicPlayer;
But it returns me null. where am I missing. Those can be done like
#JsonProperty("DetailedItems")
private DetailedItems DetailedItems;
#JsonProperty("SimilarArtists")
private SimilarArtists SimilarArtists;
#JsonProperty("RackItems")
private List<RackItems> RackItems;
But I dont want to make hard code pojos but flexible as per changeable in future.
//Main parser class
public class MainParser {
RackItemsData RackItems;
GenereData DetailedItems;
public DownloadSongsData getDownloadSongs() {
return DownloadSongs;
}
public void setDownloadSongs(DownloadSongsData downloadSongs) {
DownloadSongs = downloadSongs;
}
public GenereData getDetailedItems() {
return DetailedItems;
}
public void setDetailedItems(GenereData detailedItems) {
DetailedItems = detailedItems;
}
public RackItemsData getRackItems() {
return RackItems;
}
public void setRackItems(RackItemsData rackItems) {
RackItems = rackItems;
}
DownloadSongsData DownloadSongs;
}
// Second class
public class RackItemsData {
String Name;
String Description;
ArrayList<MainContentItemsData> MainContentItems;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public ArrayList<MainContentItemsData> getMainContentItems() {
return MainContentItems;
}
public void setMainContentItems(ArrayList<MainContentItemsData> mainContentItems) {
MainContentItems = mainContentItems;
}
}
//ThirdClass
public class MainContentItemsData {
String Name;
String Description;
ArrayList<ContentItemsData> ContentItems;
public ArrayList<ContentItemsData> getContentItems() {
return ContentItems;
}
public void setContentItems(ArrayList<ContentItemsData> contentItems) {
ContentItems = contentItems;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
//Forth class
public class ContentItemsData {
String Name;
String Description;
String Type;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getType() {
return Type;
}
public void setType(String type) {
Type = type;
}
}
//Fifth Class
public class GenereData {
MainContentItemsData Genre;
public MainContentItemsData getGenre() {
return Genre;
}
public void setGenre(MainContentItemsData genre) {
Genre = genre;
}
public RackItemsData getUserProfile() {
return UserProfile;
}
public void setUserProfile(RackItemsData userProfile) {
UserProfile = userProfile;
}
RackItemsData UserProfile;
}
//Sixth class
public class DownloadSongsData {
String Name;
String Description;
String ItemType;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
public String getItemType() {
return ItemType;
}
public void setItemType(String itemType) {
ItemType = itemType;
}
}
/////
use GSon libraru and parse data;
Gson gson = new Gson();
MainParser resultObject = gson.fromJson(jsonResultString, MainParser.class);
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.