I came across the following tutorial:
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
But this tutorial shows how to convert json to a Java object , when the json file is stored on the user's pc.
What I want to do is, when I go to the following link:
http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=[MyApiKey]&q=Toy+Story+3&page_limit=1
it returns me the following json data:
{
"total": 2,
"movies": [{
"id": "770672122",
"title": "Toy Story 3",
"year": 2010,
"mpaa_rating": "G",
"runtime": 103,
"critics_consensus": "Deftly blending comedy, adventure, and honest emotion, Toy Story 3 is a rare second sequel that really works.",
"release_dates": {
"theater": "2010-06-18",
"dvd": "2010-11-02"
},
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": 99,
"audience_rating": "Upright",
"audience_score": 91
},
"synopsis": "Pixar returns to their first success with Toy Story 3. The movie begins with Andy leaving for college and donating his beloved toys -- including Woody (Tom Hanks) and Buzz (Tim Allen) -- to a daycare. While the crew meets new friends, including Ken (Michael Keaton), they soon grow to hate their new surroundings and plan an escape. The film was directed by Lee Unkrich from a script co-authored by Little Miss Sunshine scribe Michael Arndt. ~ Perry Seibert, Rovi",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/11/13/43/11134356_mob.jpg",
"profile": "http://content6.flixster.com/movie/11/13/43/11134356_pro.jpg",
"detailed": "http://content6.flixster.com/movie/11/13/43/11134356_det.jpg",
"original": "http://content6.flixster.com/movie/11/13/43/11134356_ori.jpg"
},
"abridged_cast": [
{
"name": "Tom Hanks",
"characters": ["Woody"]
},
{
"name": "Tim Allen",
"characters": ["Buzz Lightyear"]
},
{
"name": "Joan Cusack",
"characters": ["Jessie the Cowgirl"]
},
{
"name": "Don Rickles",
"characters": ["Mr. Potato Head"]
},
{
"name": "Wallace Shawn",
"characters": ["Rex"]
}
],
"alternate_ids": {"imdb": "0435761"},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122.json",
"alternate": "http://www.rottentomatoes.com/m/toy_story_3/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/cast.json",
"clips": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/clips.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/770672122/similar.json"
}
}],
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=Toy+Story+3&page_limit=1&page=1",
"next": "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q=Toy+Story+3&page_limit=1&page=2"
},
"link_template": "http://api.rottentomatoes.com/api/public/v1.0/movies.json?q={search-term}&page_limit={results-per-page}&page={page-number}"
}
I want to store this data in a Java Object and then use it. I am a newbie in Java programming.
Thanks.
I would suggest to use something like Gson library, for parsing the Json.
Gson makes it quite elegant and simple.
However, as you are new, I would suggest you to go through the Gson Overview.
Jackson has some built-in methods to read from URLs. You can try the following (using java.net.URL):
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new URL("http://www.mydomain.com/info.json"), User.class);
Related
This is my sample JSON Response:
{
"success": true,
"details": {
"banners": [
{
"banner_id": "1",
"file_id": "368",
"title": "INANG KALIKASAN'S BAD HAIR DAY",
"description": "Et aeterno partiendo his, vim ponderum abhorreant et. Eum debet recusabo repudiandae in.",
"created": "2018-03-09 07:56:04",
"modified": "2018-04-02 09:59:54",
"deleted": "",
"file_name": "https://globegfs.imgix.net/uploads/2018-04-02/8a90371e9ad33cf06848b354b1fbd795.jpg",
"orig_file_name": "hero-1.jpg"
}
],
"recent_books": [
{
"content_id": "353",
"category_id": "24",
"title": "One Hundred Fourth Symphony, in D-major",
"author": "Franz Josef Haydn",
"description": "The last of the 12 London Symphonies written by Franz Haydn. This ebook contains copies of the 4 movements in .mid format.",
"tags": [
{
"content_id": "353",
"tag_id": "14",
"created": "2018-04-27 15:57:46",
"tag_name": "Ray Collections"
}
]
}
],
"classics": [
{
"content_id": "353",
"category_id": "24",
"title": "One Hundred Fourth Symphony, in D-major",
"author": "Franz Josef Haydn",
"description": "The last of the 12 London Symphonies written by Franz Haydn. This ebook contains copies of the 4 movements in .mid format.",
"tags": [
{
"content_id": "353",
"tag_id": "14",
"created": "2018-04-27 15:57:46",
"tag_name": "Ray Collections"
}
]
}
]
}
}
Only the banners object has a different list of contents. All the succeeding Json Elements will have the same contents but in a list, having its Json Node its actual title. How can I map this into a HashMap?
I figured it will look something like this:
private List<GFSBannerResponse> banners;
private List<HashMap<String, List<GFSContentResponse>>> featuredContent;
but I still don't have an idea on how to implement this. I am using Retrofit 2.0 and Gson.
I ended up implementing it this way:
#SerializedName("details")
#Expose
private JsonElement details;
I just used JsonParser to parse the content to a JsonElement. Stuck with GSON for all of this, although this wasn't the ideal implementation. Will try to implement a custom Deserializer in the future.
Am a new bee to vaadin. I have to show the data from a JSON file (which is fetching from MySQL db) in Grid/Table(vaadin). I am able show the data in table if JSON in the below format.
[
{
"id": "ex-wardrobe",
"productId": "ex-wardrobe",
"name": "exWardrobe",
"desc": "Some description",
"dimension": "WxDxH 148\" X 24\" X 112\" ",
"category": "Bedroom",
"subcategory": "Wardrobe",
"categoryId": "bedroom",
"subcategoryId": "wardrobe",
"tags": "all, Space Design Bedroom, Space Details Wardrobe",
"designer": "hb",
"curr": "INR",
"popularity": "1",
"relevance": "1",
"shortlisted": "1",
"likes": "1",
"createDt": "",
"pageId": "ex-wardrobe",
"styleName": "Fresh",
"styleId": "cfresh",
"priceRange": "Premium",
"priceId": "premium",
"defaultPrice": "123",
"defaultMaterial": "MDF ",
"defaultFinish": "LAMINATE"
}
]
But, if i get JSON(data is related to same product) in the below format am unable to add data in table.
[
{
"id": "ex-wardrobe",
"productId": "ex-wardrobe",
"name": "exWardrobe",
"desc": "Some description",
"dimension": "WxDxH 148\" X 24\" X 112\" ",
"category": "Bedroom",
"subcategory": "Wardrobe",
"categoryId": "bedroom",
"subcategoryId": "wardrobe",
"tags": "all, Space Design Bedroom, Space Details Wardrobe",
"designer": "hb",
"curr": "INR",
"popularity": "1",
"relevance": "1",
"shortlisted": "1",
"likes": "1",
"createDt": "",
"pageId": "ex-wardrobe",
"styleName": "Fresh",
"styleId": "cfresh",
"priceRange": "Premium",
"priceId": "premium",
"defaultPrice": "123",
"defaultMaterial": "MDF ",
"defaultFinish": "LAMINATE",
"mf": [
{
"basePrice": "123",
"material": "MDF ",
"finish": "LAMINATE"
}
],
"images": [
"066___ex_WARDROBE_Dim.jpg",
"067___ex_WARDROBE_close_door.jpg",
"068___ex_DOVE_dim.jpg"
],
"components": [],
"accessories": []
}
]
This is the code which am using to show JSON data in table,
Table grid = new Table();
root.addComponent(grid);
grid.setStyleName("iso3166");
grid.setPageLength(6);
grid.setSizeFull();
grid.setSelectable(true);
grid.setMultiSelect(false);
grid.setImmediate(true);
grid.setColumnReorderingAllowed(true);
grid.setColumnCollapsingAllowed(true);
try {
JSONArray products = productsDataProvider.getCatalogs();
JsonContainer dataSource =
JsonContainer.Factory.newInstance(products.toString());
grid.setContainerDataSource(dataSource);
grid.setColumnReorderingAllowed(true);
grid.setWidth("98%");
grid.addStyleName(ChameleonTheme.TABLE_STRIPED);
} catch (IllegalArgumentException ignored) {
}
grid.setWidth("100%");
grid.setHeight("100%");
root.addComponent(grid);
Am stuck on this and i have sleepless night on this. Million tons of thanks in advance. I hope you GURU's can help me in this :)
Sorry not vaadin expert. See it first time and like it. I guess your problem are the arrays inside your object. I mean this:
"mf": [
{
"basePrice": "173881",
"material": "MDF ",
"finish": "LAMINATE"
}
],
"images": [
"066___ex_WARDROBE_Dim.jpg",
"067___ex_WARDROBE_close_door.jpg",
"068___ex_DOVE_dim.jpg"
],
"components": [],
"accessories": []
No idea how the component should display this. Have you tried it without mf, images, components and accessories?
You are using a very simple JSONContainer. As can be seen in the source code, this implementation does not support nested / compound elements and arrays.
First you have to ask yourself how these complex objects need to be displayed (UX), especially the "mf" field.
UPDATE
Simple compound objects (like "simpleCompound": {"name": "foo", number: 123}) can be shown in a table column (not supported by the JSONContainer you use, but similar functionality is available by the BeanItemContainer, so look there for how to implement this functionality).
The array fields are more problematic from a UX standpoint. Mostly this information is only shown on demand or in separate panels. The Vaadin Grid component offers the possibility to show a details view, see the wiki. Maybe that will fit your requirements.
Currently nested json data is not supported unless you create your own advance template for that. There is currently an online json container application demo that is used to test if the data is really json or json array but not nested. Then it displays that data in grid table. So you can use this to verify your data.
You can also get the application template with source code on github
I'm just wondering if someone can help me..
So, I have an API that I have developed using Fractal to parse the objects to generate some nice JSON to be consumed by an android app i'm making.
The JSON output looks a little something like this:
{
"data": [
{
"id": 1,
"name": "John Smith",
"description": "Information about John Smith",
"games": {
"data": [
{
"name": "Batman Arkham City",
"description": "Information about Game 1"
},
{
"name": "Silent Hill",
"description": "Information about Game 2"
}
]
}
}
]
}
To parse this using Gson, I obviously have to create a Person model which has an ArrayList The thing is.. Note the data key? How do I instruct Gson to parse this? I understand removing that to have the JSON look like this:
{
"data": [
{
"id": 1,
"name": "John Smith",
"description": "Information about John Smith",
"games": [
{
"name": "Batman Arkham City",
"description": "Information about Game 1"
},
{
"name": "Silent Hill",
"description": "Information about Game 2"
}
]
}
]
}
My Person model looks a little something like this:
public class Person
{
public String name;
public ArrayList<Game> games;
Like I said, removing the data key would allow me to parse the data into Java models like so:
peopleArray = jsonObject.getJSONArray( "data" );
Type listType = new TypeToken<ArrayList<Person>>() {}.getType();
ArrayList<Person> result = new Gson().fromJson( peopleArray.toString(), listType );
So basically, is there any way I can tell Gson that the Games array will have a data key? Sorry for the information overload and hopefully that'll make sense?
Ta
Managed to solve this using custom GSON serialisers/deserialisers.
http://www.studytrails.com/java/json/java-google-json-custom-serializer-deserializer.jsp
I am developing first time in android and i have never used json data before. I will develop an application of event calendar of my university. We developed web version application in Django and we implement tastypie (restapi) so i need to use this json data for android mobile version. My json data is like this :
{
"meta": {
"limit": 20,
"next": null,
"offset": 0,
"previous": null,
"total_count": 5
},
"objects": [{
"Location": "Z011",
"Notes": "asdf",
"Title": "Literature Talking",
"id": 3,
"resource_uri": "/api/v1/Events/3/"
}, {
"Location": "Batı Kampüsü, Sinema Salonua",
"Notes": "sd",
"Title": "TARİHÇE KONFERANSLARI SERİSİ 25",
"id": 4,
"resource_uri": "/api/v1/Events/4/"
}, {
"Location": "in Campus",
"Notes": "afafdf",
"Title": "Self-Assessment Project",
"id": 5,
"resource_uri": "/api/v1/Events/5/"
}, {
"Location": "Kütüphane",
"Notes": "fs",
"Title": "51.Kütüphane Haftası",
"id": 6,
"resource_uri": "/api/v1/Events/6/"
}]
}
how can I parse this Json data in android studio?
Using below code you will be able to get Title and Location
JSONObject obj=new JSONObject(response);//This is response from webservice
String totalCount = obj.getJSONObject("meta").getString("total_count"); //for getting total_count
JSONArray json_array = obj.getJSONArray("objects");
for(int j=0;j<json_array.length();j++) {
String title = json_array.getJSONObject(j).getString("Title");
String location= json_array.getJSONObject(j).getString("Location");
}
Use this website to help you view the Json structure better
http://www.jsontree.com/
What you have is a Json Object since it starts and ends with curly braces.
For example if I had a Json as {"Id":"1"}
The Key is "Id" and the value is "1"
A Json object can have a Json inside the value as well(Which is your case)
And example is {"Id":{"Place1":"1", "Place2":"2"}}
So the Key is "Id" and it has the value "Place1":"1", "Place2":"2"
So the value is also a Json.
It can get a little messy with Jsons in Jsons.
Here is a good tutorial on parsing Json
http://www.tutorialspoint.com/android/android_json_parser.htm
Say I have a JSON array similar to the following:
[
{
"title": "This is a title",
"year": 2013,
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
"thumbsdown": 256
}
},
{
"title": "This is a title",
"year": 2013,
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
"thumbsdown": 256
}
}
]
And the required output is a JSON array like this:
[
{
"title": "This is a title",
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
}
},
{
"title": "This is a title",
"images": {
"image": "http://........jpg",
},
"ratings": {
"thumbsup": 1053,
}
}
]
Iv'e been researching and it's suggested that the most efficient way would be to parse it using the Jackson streaming API. This is for use on a PaaS with limited memory, so I wish to keep the memory usage to the bare minimum.
Is the best way to parse the JSON with Jackson Streaming API, and construct a new JSON array at the same time or simply remove the elements somehow?
I did something similiar with XML once. You can have the requestor tell you what fields you want to get back, and have it only emit those. In my case I had no control over the 3rd party axis xml view, but once I had the view, when I asked for things from it if it was already there I could give back just the pieces I was interested in. As a bonus, if you are marshalling or unmarshalling real java objects from the JSON after getting the json or XML you don't need to build the part of the object graph you don't care about.