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
Related
I am new in android JSON parsing android.
Below I mentioned my JSON value, please give the solution to how to parse the JSON value, thanks in advance my JSON Data:
Here I have category, categorybook, subcategory inside have subbook. I want to parse all the value and store it into sqlite with separate.
Like category book and sucategory book are stored seperate column in android sqlite table:
[
"category": {
"id": "1",
"name": "Education",
"categorybooks": [],
"subcategory": [
{
"id": "1",
"name": "tamil",
"subcategorybooks": []
},
{
"id": "2",
"name": "english",
"subcategorybooks": []
},
{
"id": "5",
"name": "maths",
"subcategorybooks": []
},
{
"id": "6",
"name": "science,
"subcategorybooks": []
},
{
"id": "7",
"name": "social",
"subcategorybooks": []
}
}
]
Here i have category 2 and its sub category books:
[
"category": {
"id": "2",
"name": "sports",
"categorybooks": [
{
"id": "4",
"name": "football",
},
{
"id": "5",
"name": "cricket",
}
],
"subcategory": []
}
]
First of all, you will need the VolleyLibrary. Then, you will need the GSON library. When creating GSON Request, you put the Object you want to get deserialized automatically from JSON, so you wont have to parse it manualy.
Second thing, you would want to create a db class that extends SQLiteHelper. When you create database, add the methods for adding, update and removing a row for every table that you create.
Below are the links that you need.
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
https://medium.com/android-news/android-networking-i-okhttp-volley-and-gson-72004efff196#.wp5lstsfv
http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
I will assume you already have the content of your json, if not you can use any Http Connection to get the content.
You can use Gson to parse your json content, first of all, you need to create your models based on your Json:
//note: Gson identify the attributes name as the same of from your
//json, if not you have to put an annotation above each attribute of
//your class:
public class Category(){
int id;
String name;
List<CategoryBook> categoryBooks;
}
public class CategoryBook(){
int id;
String name;
}
public class SubCategory(){
//Based on your json I will assume the attribute of this class
// is a model that have a list of an object that have an id and a name
//and a list of subcategorybooks
}
public class SubCategoryBooks(){
//class attributes that you not mentioned in your json
}
Then you just need to parse your object from content using gson,
if you have some doubts about how to parse using Gson follow this tutorial
For insert into database separate, you already have your objects with getters and setters, for example
you can get the List<CategoryBook> from your CategoryModel, then your can insert this list
inside a separate table of your database.
Hope It's Help you
JSONObject jsonObject = new JSONObject();
jsonObject.put("category",loaddata());
public JSONObject loaddata(){
JSONObject jsonObject = new JSONObject();
jsonObject.put("id","1");
jsonObject.put("name","Education");
jsonObject.put("categorybooks",addcategorybooks());
jsonObject.put("subcategory","addsubcategory()");
return jsonObject;
}
public JSONArray addcategorybooks(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
JsonArray.put(jObj);
return JsonArray;
}
public JSONArray addsubcategory(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
jObj.put("subcategorybooks", addsubcategorybooks());
JsonArray.put(jObj);
return JsonArray;
}
public JSONArray addsubcategorybooks(){
JSONArray JsonArray = new JSONArray();
JSONObject jObj = new JSONObject();
jObj.put("id", "1");
jObj.put("name", "Foot Ball");
JsonArray.put(jObj);
return JsonArray;
}
If i understood you correctly, the main problem is to get java model object from json.
There are several ways to do it. The most common are:
Using built-in tools to operate with Json. In this case you get org.json.JSONObject and get values using it's methods. See details f.e. here
Using gson library. In this case you create model class and you can fill the object with one code line. smth like Category category = gson.fromJson(yourJsonString, Category.class); See details in official tutorial
I try to save properties in a Couchbase-document in Android.
The properties hold a JSONArray with several JSONObjects.
When I do document.putproperties(myproperties) a couchbaseliteexception with state 400 and the message "bad or missing json" is thrown".
So the JSONArray looks like:
"some_prop" -> "[
{
"content":"someContent",
"key2":"",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
},
{
"content":"Some other content",
"key2":"something",
"key3":"",
"key4":"",
"month":8,
"day":3,
"key5":115
}]"
Can anyone tell me whats the problem with this JSON?
EDIT:
the JSONArray with the corresponding key is saved in a hashmap like it is explained in:
http://developer.couchbase.com/mobile/develop/guides/couchbase-lite/native-api/document/index.html
EDIT 2:
The Method where the update is executed and the JSONArray is filled:
private void updateDoc(ArrayList<MyObject> objects) {
Document document = getDocument();
// Update the document with more data
Map<String, Object> updatedProperties = new HashMap<>();
JSONArray objectArray = new JSONArray();
//fill array with data
for(MyObject element : objects) {
JSONObject jsonObjects = element.toJSONObject();
if(jsonObjects != null) {
objectArray.put(jsonObjects);
}
}
//set data to property map
updatedProperties.put(MYOBJECT_PROP_IDENTIFIER, objectArray);
try {
// Save properties to the Couchbase local Couchbase Lite DB
document.putProperties(updatedProperties);
} catch (CouchbaseLiteException e) {
}
}
Not sure if this is what you're looking for,
You can also use something like http://jsonlint.com to verify your son
{
"some_prop": [
{
"content": "someContent",
"key2": "",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
},
{
"content": "Some other content",
"key2": "something",
"key3": "",
"key4": "",
"month": 8,
"day": 3,
"key5": 115
}
]
}
Finally I found a solution to the problem:
I don't use JSONObject or JSONArray anymore but save my data in ArrayList and put each element directly into the database. so i don't have an Array with all the elements which but a lot of single elements direktly in the document. To accesss them later I save also the number of elements in the DB. Each element has the index as a prefix so it can be identified later on.
That's not quite a nice way but it works..
My JSON file contains strings with the same keys but some of them doens't appear for some strings. For example:
{
"city": "CB1 2BH Cambridge",
"addr": "Devonshire Road 1",
"title": "Devonshire Arms",
"phone": "+44 1223 6610"
},
{
"city": "E8 1JH London",
"addr": "Amhurst Road 90",
"title": "Pembury Tavern",
"web": "http://www.individualpubs.co.uk/pembury/"
},
{
"web": "http://bandholmhotel.dk/",
"title": "Bandholm Hotel",
},
{
"city": "00100 Helsinki",
"addr": "Pohjoinen Rautatiekatu 23",
"title": "Helkan Baari",
"country": "FI"
},
How to correctly parse it in android?
Considering this is your JSONArray,
Try to do as following,
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jObj = (JSONObject) jsonProductArray.getJSONObject(i);
String city = jObj.optString("city", "cityDefaultValue");
String addr = jObj.optString("addr", "addDefaultValue");
String title = jObj.optString("title", "titleDefaultValue");
String phone = jObj.optString("phone", "phoneDefaultValue");
}
One possible solution can be to have a modal class and use Gson library to parse the Json.
You can set some default values in your modal class, for keys whose value is not found in Json
Create an model class with the key of the json and parse it to the model class using gson.
A a = gson.fromJson(jsonRes.toString(),A.class);
here A is your model class and a is the instance of A
You can use Gson library.
Create something like that
class SomeObjects {
#SerializedName("city")
private String mCity;
#SerializedName("addr")
private String mAddres;
...
}
and in then
SomeObject obj = new Gson.fromJson(jsonString, SomeObject.class);
You also can sirialize right into array
I want to parse json, but I didn't find how to parse array from this structure:
{
"0": {
"title": "\u0417\u041d: \u0415\u0432\u0440\u043e\u043f\u0435\u0439\u0446\u044b ",
"date": "2011-11-26 14:33:00"
},
"1": {
"title": "\u041a\u0430\u043a\u0430\u044f ",
"date": "2011-11-25 13:55:00"
},
"2": {
"title": "\u0423\u043a\u0440\u0430\u0438\u043d\u0430",
"date": "2011-11-25 11:15:00"
},
"3": {
"title": "\u0423\u0416\u0421\u041a ",
"date": "2011-11-24 15:45:00"
},
"time": 0.03944993019104
}
See, the problem is you don't actually have an array. You have a series of dictionaries, keyed by index. The only way to do this is to iterate over each numerical key, and add its value to a list.
Here's some pseudocode to help you get started:
yourArray = new Array(yourJSON.keys.length)
for key in yourJSON.keys:
yourArray.put(yourJSON[key], int(key))
You'll need to make a new array object whose length is equal to the number of keys. Then, put each of the values for each key at index key.
Try parsing these as JSONObject and then accessing it's values keys provided.
To be more specific:
try {
JSONObject foo = new JSONObject(youJsonString);
foo.get(name)
} catch (JSONException e) {
//handle exceptions
}
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;
}