First of all Sorry for the really long post, now
And this is my class structure, no idea if it's right or wrong
public class GoogleResponse {
public ResponseDate responseData;
public String responseDetails;
public String responseStatus;
}
public class ResponseData {
public List<Result> results;
//public Cursor cursor;
}
public class Result {
public String titleNoFormatting;
public String unescapedUrl;
}
And this is the code for deserialization
Gson gson = new Gson();
GoogleResponse data[] = gson.fromJson(s, GoogleResponse[].class);\\s is the JSON string
In this program i just want to extract titlenoformating and unescapedurl, that's why i left out rest of the content from the class's.
I don't know if this is right or wrong, but when i do System.out.print(data);
I get nothing in logcat, i don't know how to access the data that is stored in data[].
What i want is to populate a listview using the titleNoFormating and open the corresponding unescapedurl on clicking any results via intent.
EDIT:
{
"results": [
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.mediafire.com/?zcnqy5mmwmj",
"url": "http://www.mediafire.com/%3Fzcnqy5mmwmj",
"visibleUrl": "www.mediafire.com",
"cacheUrl": "http://www.google.com/search?q=cache:f6cE2lmmCioJ:www.mediafire.com",
"title": "Redman Funk From <b>Hell</b> 2010.zip",
"titleNoFormatting": "Redman Funk From Hell 2010.zip",
"content": "Redman Funk From <b>Hell</b> 2010.zip. <b>...</b> Share “Redman Funk From <b>Hell</b> 2010.zip”. Info . Facebook/Twitter. Email. Share by IM. Embed. HTML Embed Code. Sharing URL <b>...</b>",
"clicktrackUrl": "//www.google.com/url?q=http://www.mediafire.com/?zcnqy5mmwmj&sa=T&usg=AFQjCNGhKqruZDyj614zfvjuitABOJFrNQ&ei=BUQdTtbGLeWTmQWElOHzBw&ved=0CAQQFjAA"
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.mediafire.com/?ymto5mjznwz",
"url": "http://www.mediafire.com/%3Fymto5mjznwz",
"visibleUrl": "www.mediafire.com",
"cacheUrl": "http://www.google.com/search?q=cache:aXARYHERXiQJ:www.mediafire.com",
"title": "This Routine is <b>Hell</b> - The Verve Crusade.zip - This, Routine, is <b>...</b>",
"titleNoFormatting": "This Routine is Hell - The Verve Crusade.zip - This, Routine, is ...",
"content": "Debut full-length The Verve Crusade by hardcore punk band This Routine is <b>Hell</b> from the Netherlands. Released by Shield Recordings in 2010.",
"clicktrackUrl": "//www.google.com/url?q=http://www.mediafire.com/?ymto5mjznwz&sa=T&usg=AFQjCNGd4xVGQkOlb8TMCdpH5tEIn2Ln5A&ei=BUQdTtbGLeWTmQWElOHzBw&ved=0CAYQFjAB"
}
]
}
This becomes valid so i guess i'll have to make up mu own method to get out this content
when i do System.out.print(data); I get nothing in logcat
Use android.util.Log.(), not System.out.println();
Concerning parsing the JSON, unfortunately the JSON listed in the original question is invalid, which leaves folks that might help guessing a bit. And the example JSON on Google's own search API documentation page is also invalid (though in a different way) -- it escapes the '[' and ']' characters, but the JSON spec does not allow those characters to be escaped.
Following is a corrected version of the example JSON from the Google search API documentation.
{
"responseData": {
"results": [
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://en.wikipedia.org/wiki/Paris_Hilton",
"url": "http://en.wikipedia.org/wiki/Paris_Hilton",
"visibleUrl": "en.wikipedia.org",
"cacheUrl": "http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org",
"title": "<b>Paris Hilton</b> - Wikipedia, the free encyclopedia",
"titleNoFormatting": "Paris Hilton - Wikipedia, the free encyclopedia",
"content": "[1] In 2006, she released her debut album..."
},
{
"GsearchResultClass": "GwebSearch",
"unescapedUrl": "http://www.imdb.com/name/nm0385296/",
"url": "http://www.imdb.com/name/nm0385296/",
"visibleUrl": "www.imdb.com",
"cacheUrl": "http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com",
"title": "<b>Paris Hilton</b>",
"titleNoFormatting": "Paris Hilton",
"content": "Self: Zoolander. Socialite <b>Paris Hilton</b>..."
}
],
"cursor": {
"pages": [
{
"start": "0",
"label": 1
},
{
"start": "4",
"label": 2
},
{
"start": "8",
"label": 3
},
{
"start": "12",
"label": 4
}
],
"estimatedResultCount": "59600000",
"currentPageIndex": 0,
"moreResultsUrl": "http://www.google.com/search?oe=utf8&ie=utf8..."
}
},
"responseDetails": null,
"responseStatus": 200
}
And here is an example program using Gson to deserialize this JSON to a Java data structure, and then retrieving the two target data elements.
import java.io.FileReader;
import java.math.BigInteger;
import java.util.List;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
Response response = gson.fromJson(new FileReader("input.json"), Response.class);
for (Result result : response.responseData.results)
{
System.out.println("titleNoFormatting: " + result.titleNoFormatting);
System.out.println("unescapedUrl: " + result.unescapedUrl);
}
// output:
// titleNoFormatting: Paris Hilton - Wikipedia, the free encyclopedia
// unescapedUrl: http://en.wikipedia.org/wiki/Paris_Hilton
// titleNoFormatting: Paris Hilton
// unescapedUrl: http://www.imdb.com/name/nm0385296/
}
}
class Response
{
ResponseData responseData;
String responseDetails;
int responseStatus;
}
class ResponseData
{
List<Result> results;
Cursor cursor;
}
class Result
{
String GsearchResultClass;
String unescapedUrl;
String url;
String visibleUrl;
String cacheUrl;
String title;
String titleNoFormatting;
String content;
}
class Cursor
{
List<Page> pages;
BigInteger estimatedResultCount;
int currentPageIndex;
String moreResultsUrl;
}
class Page
{
int start;
int label;
}
Related
this below json result sent from server for my app, all_food is object which keys started with string with number such as list1, list2 or list9 and lists nested all_foods have an number for keys, this structure is very difficult for me to know how can i make class structure for that
{
"all_foods": {
"list1": {
"1": "---------------",
"5": "---------------"
},
"list2": {
"1": "---------------",
"3": "---------------"
},
"list9": {
"1": "---------------",
"4": "---------------",
"6": "---------------"
}
},
"show_mixture": false,
"User_status": 2,
"lists": [
{
"UserDailyList": {
"id": "142885",
"created": "2017-08-06 22:12:56",
"modified": "2017-08-06 22:12:56"
},
"foods": {
"1": {
"meal": "---------------",
"food": "---------------"
},
"2": {
"meal": "---------------",
"food": "---------------"
},
"3": {
"meal": "---------------",
"food": "---------------"
}
}
}
],
"error": 1,
"message": "",
"condition": {
"code": "7",
"message": "-------",
"token": 10
}
}
how can i make this structure on java class? Thanks in advance
Well, two ways
You could learn the whole object modelling in Java, create POJO class which contain another class and so on.
Or you could use an online tool create the POJO from any JSON.
Two google search results for you, you can search for
JSON to POJO Online
and check more links there.
Link 1
Link 2
assuming you are using GSON
class FoodResponse{
#SerializedName("all_foods")
Map<String,Map<String,String>> allFood;
#SerializedName("show_mixture")
boolean showMixture;
///.. and so on
}
usually, with such unnecessarily complex and poorly designed JSON I recommend deserializing it like this:
new Gson().fromJson(json, Map.class); //or just Object.class
which returns a LinkedTreeMap of LinkedTreeMaps of LinkedTreeMaps (..n)
which you can browse by key/value and extract the data you need.
You won't be able to create a proper response model for a JSON that hasn't been generated from a proper JSON model on the backend. It is a common practice to fist-fight backend devs to have them send good json :)
//Basic skeleton of pojo class
class AllFoods {
List<String> l1 = new ArrayList<>();
List<String>[] arrayOfList = new List[3]; //In case if we know how //many arraylist items are added,
String show_mixture;
String User_status;
List<String> l1sts = new ArrayList<>();
String UserDailyList;
String id;
String created;
String modified;
List<String> foodsArray= new List[3]; //if we know the range
List<String> foodsList = new ArrayList<>();
String error;
String message;
List<String> condition = new ArrayList<>();
}
//Then we need to have constuctors and add the values and have them in arrayofList
Following is my POJO class
public class Favourite {
public static List<LocalTrack> favourite;
public Favourite() {
favourite = new ArrayList<>();
}
public List<LocalTrack> getFavourite() {
return favourite;
}
}
Im saving the json as follows in my shared preference
public static class SaveFavourites extends AsyncTask {
#Override
protected Void doInBackground(Void... params) {
String json5 = gson.toJson(favourite);
prefsEditor.putString("favouriteTracks", json5);
prefsEditor.commit();
return null;
}
}
Following are the fields which refers to POJO class
public static Favourite favouriteTracks =new Favourite();
public static List favourite = favouriteTracks.getFavourite();
Im using the following class to access the json stored as follows,
String json5 = mPrefs.getString("favouriteTracks", "");
Arrays.toString(gson.fromJson(json5, Favourite[].class))
But it always returns empty array though it was not empty while saving. When im saving, it has got a json array with multiple json objects but while retrieving, it is an empty json array.
How can I be able to sort this out?
Following is my json response
[
{
"album": "http://MyMp3Song.Com",
"artist": "04 - Thai Mannai Vanakka",
"index": "#",
"path": "/storage/sdcard1/Download/04 - Thai Mannai Vanakkam(MyMp3Song.Com).mp3",
"title": "04 - Thai Mannai Vanakkam(MyMp3Song.Com)",
"duration": 369424,
"id": 32004
},
{
"album": "http://MyMp3Song.Com",
"artist": "04 - Thai Mannai Vanakka",
"index": "#",
"path": "/storage/sdcard1/Download/04 - Thai Mannai Vanakkam(MyMp3Song.Com).mp3",
"title": "04 - Thai Mannai Vanakkam(MyMp3Song.Com)",
"duration": 369424,
"id": 32004
}
]
I have tried to parse this JSON using gson but I couldn’t.
Can anyone help me to parse this JSON using gson?
JSON:
{
"status": "ok",
"results": {
"favourites": [
{
"id": "UB3172",
"name": "Masdar Headquarters"
},
{
"id": "UB1438",
"name": "Guggenheim Abu Dhabi on Saadiyat Island"
},
{
"id": "UB4838",
"name": "Watani Residential Development in Abu Dhabi - 600 Villas and 48 Buildings"
},
{
"id": "UB4795",
"name": "Two Mosques in Mohammed Bin Zayed City"
},
{
"id": "UB1274",
"name": "2 Workers Residential City at Al Ain Industrial City"
}
]
}
}
I tried this one for JSON parser class:
public class ProjectList {
public String status;
public String results;
public class Favourites{
public String id;
public String name;
}
}
In MainActivit
Reader reader = new InputStreamReader(result);
Gson gson=new Gson();
List<ProjectList.Favourites> fav=new ArrayList<ProjectList.Favourites>();
fav=Arrays.asList(gson.fromJson(reader, ProjectList.Favourites.class));
Create a POJO class as follows
class MyResponse {
public String status;
public Result results;
public static class Favourites {
public String id;
public String name;
}
public static class Result {
public List<Favourites> favourites;
}
}
and pass it to gson as
MyResponse response = new Gson().fromJson(yourResponse, MyResponse.class);
idea is that maintain the hierarchy of key-value pairs with appropriate POJO's
You can generate your pojos here : http://www.jsonschema2pojo.org/
Sometimes gson cannot convert your objects from json. In this case you have to write your own deserializer and use it with gson builder.
Edit: If you use proguard before release your project (if you set proguard to change your pojos variable names) gson cannot match class variable names, json names so it cannot convert your objects. You have to add #SerializedName("your_variable_name") annotaion.
Try this way,hope this will help you to solve your problem.
String jsonRespone = "{\"status\":\"ok\",\"results\":{\"favourites\":[{\"id\":\"UB3172\",\"name\":\"Masdar Headquarters\"},{\"id\":\"UB1438\",\"name\":\"Guggenheim Abu Dhabi on Saadiyat Island\"},{\"id\":\"UB4838\",\"name\":\"Watani Residential Development in Abu Dhabi - 600 Villas and 48 Buildings\"},{\"id\":\"UB4795\",\"name\":\"Two Mosques in Mohammed Bin Zayed City\"},{\"id\":\"UB1274\",\"name\":\"2 Workers Residential City at Al Ain Industrial City\"}]}}";
String status;
ArrayList<HashMap<String,String>> favouritesList = new ArrayList<HashMap<String, String>>();
try{
JSONObject responseJson = new JSONObject(jsonRespone);
status = responseJson.getString("status");
JSONArray favouriteJsonArray = responseJson.getJSONObject("results").getJSONArray("favourites");
for (int i=0;i<favouriteJsonArray.length();i++){
HashMap<String,String> favourite = new HashMap<String, String>();
favourite.put("id",favouriteJsonArray.getJSONObject(i).getString("id"));
favourite.put("name",favouriteJsonArray.getJSONObject(i).getString("name"));
favouritesList.add(favourite);
}
System.out.print("status : "+status);
for (HashMap<String, String> favourite : favouritesList) {
System.out.print("id : "+favourite.get("id"));
System.out.print("name : "+favourite.get("name"));
}
}catch (Throwable e){
e.printStackTrace();
}
I'm using Jackson 2.3 and I'm having some problems deserializing.
I have these class and interface:
FollowValue:
public class FollowValue implements Value{
#JsonProperty("id");
public long id;
#JsonProperty("time_creation")
#JsonDeserialize(using = DateDeserializer.class)
public Date timeCreation;
#JsonProperty("follower")
private User follower;
#JsonProperty("user")
private User user;
#Override
public long getId() {
return id;
}
#Override
public Date getTimeCreation() {
return timeCreation;
}
}
Value:
public interface Value {
public long getId();
public Date getTimeCreation();
}
When I read the FollowValue like this:
FollowValue value = mapper.readValue(valueNode.traverse(), FollowValue.class);
No exception is showed and follower and user are null. I've searched for a solution but I only find documentation for previous versions of Jackson. How can I deserialize this?
Thanks!
This is the JSON I'm trying to parse:
"type": "Follow",
"value": {
"id": 205,
"time_creation": "2014-03-04T14:54:53+0100",
"follower": {
"id": 62,
"username": "email#email.com",
"fullname": "Meri Riera",
},
"user": {
"id": 24,
"username": "email#email.com",
"fullname": "Héctor",
}
}
You can try with this:
mapper.readValue(valueNode.traverse(objectCodec), FollowValue.class);
I don't know if it's the best approach, but it works for me.
Since your jsonc data does not fit in a format of FollowValue format I think it won't be parsed.
Try to annotate your main entity with #JsonRootName(value = "value")
Then after instantiating your ObjectMapper object, configure it with:
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Hope this will solve your problem.
Can anyone please help me to convert this JSON to Java Object. I usually use GSON, but it seem this time it is not working for me. The problem is that I want to create an Object that contains
Class JsonGotText{
String status;
List<Object> result;
}
But all the Object in List is all difference properties... So I don know how to do to let Gson Map it correctly
{
"status": 0,
"result": {
"1346053628": {
"type": "default",
"decorated_time": 1346053628,
"guidOwner": 13716,
"friendGuid": 3264,
"action_type": "friend",
"summary": " is now a friend with ",
"annotation": null,
"group": ""
},
"1346051675": {
"type": "event",
"decorated_time": 1346051675,
"guidOwner": 90,
"title": null,
"action_type": "event_relationship",
"summary": "river:event_relationship:object:event",
"annotation": null,
"group": ""
},
"1346048488": {
"type": "event",
"decorated_time": 1346048488,
"guidOwner": 90,
"title": null,
"action_type": "event_relationship",
"summary": "river:event_relationship:object:event",
"annotation": null,
"group": ""
}
}
}
Try using
Class JsonGotText{
String status;
HashMap<String, Object> result;
}
If performance is not key criteria here. You better use 'JSONObject' without worrying the structure of JSON String.
Ideally, you should write a POJO. Say EventPOJO that has attributes same as as each result object holds and then make the Java class as
Class JsonGotText{
String status;
HashMap<String, EventPOJO> result;
}
you may have to use a type token see here, but will save your efforts later.
Update
It seems the sentence above sounds confusing. Here is clarification what I wanted EventPOJO to represent to. The EventPOJO will represents things like
{
"type": "event",
"decorated_time": 1346048488,
"guidOwner": 90,
"title": null,
"action_type": "event_relationship",
"summary": "river:event_relationship:object:event",
"annotation": null,
"group": ""
}
Update1 #LalitPoptani asked for exact working code. Here it is!
Here is an working example:
public class Test {
private static String json =
"{"+
"\"status\": 0,"+
"\"result\": {"+
"\"1346053628\": {"+
"\"type\": \"default\","+
"\"decorated_time\": 1346053628,"+
"\"guidOwner\": 13716"+
"},"+
"\"1346051675\": {"+
"\"type\": \"event\","+
"\"decorated_time\": 1346051675,"+
"\"guidOwner\": 90"+
"},"+
"\"1346048488\": {"+
"\"type\": \"event\","+
"\"decorated_time\": 1346048488,"+
"\"guidOwner\": 90"+
"}"+
"}" +
"}";
public static class Event{
String type;
Long decorated_time;
Integer guidOwner;
}
public static class JSON{
Integer status;
HashMap<Long, Event> result;
}
public static void main(String[] args){
Gson gson = new Gson();
System.out.println("JSON: " + json);
JSON j = gson.fromJson(json, JSON.class);
for(Entry<Long, Event> e: j.result.entrySet()){
System.out.println(e.getKey() + ": " + e.getValue().guidOwner);
}
}
}