The Easiest Way To Parse/Read Json - android

I was searching for a Way to Parse/Read JSON data Easily. Wile Searching I discovered this and thought of sharing it.
Suppose following Json Data:
[
{
"id": 912345678901,
"text": "How do I read JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
},
{
"id": 912345678902,
"text": "#android_newb just use android.util.JsonReader!",
"geo": [50.454722, -104.606667],
"user": {
"name": "jesse",
"followers_count": 2
}
}
]}
see the answer below.

By far the easierst way would be to use Gson to parse Json data to Java objects.
This site even lets you automatically create Java classes from an example JSON input (some adjustments to the classes might be necessary).
No need to do this on your own, use tools ;)

Gson is the best library for converting JSON to object and object to JSON

Related

How can I sort categories using json?

I have an android app which fetches data from json file and displays it in the app, but when rendered it appears randomly and unordered as in json file
This is the simple code used in json:-
"Categories": [
{
"name": "text1"
},
{
"name": "text2"
},
{
"name": "text3"
}
What I want is to arrange these categories to appear in the application in the same order as the one you formatted in the json file
Can anyone help me here? Thanks!

Android - Handling different types of JSON data from Django backend

I get the following output from a request:
{
"allposts": [
{
"created": "2019-07-08T12:25:34.732217Z",
"description": "My First ImagePost",
"id": 1,
"imagepostdata": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg",
"owner": "http://127.0.0.1:8000/users/getUserById/1/",
"profilePhotoOfUser": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg",
"type": "ImagePost",
"url": "http://127.0.0.1:8000/posts/getImagePostById/1/"
},
{
"audio": "http://127.0.0.1:8000/media/Audios/None/placeholder.3gp",
"clique": "http://127.0.0.1:8000/cliques/getCliqueById/1/",
"created": "2019-07-08T12:25:56.748829Z",
"id": 2,
"image": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg",
"owner": "http://127.0.0.1:8000/users/getUserById/1/",
"profilePhotoOfUser": "http://127.0.0.1:8000/media/Images/None/placeholder.jpg",
"text": "My First TextPost",
"type": "TextPost",
"url": "http://127.0.0.1:8000/posts/getTextPostById/2/",
"video": "http://127.0.0.1:8000/media/Videos/None/placeholder.mp4"
}
]
}
The first item in the JSON array represents an image post and the second item represents a text post.
I have image and text posts as post type. Here, you can see that the server gives the requesting client the different types collected as one output. The fields of the items can be different.
For ex.: imagepostdata vs. textpostdata.
Now, I am not sure how to define the model classes in my Android project. I use Retrofit as networking library combined with Gson.
My question: It is enough to write the ImagePost and TextPost model classes separately and let Retrofit/Gson handle the rest ?
Or should I copy/paste the output to http://www.jsonschema2pojo.org/ and get only one model class for the different items.
I am asking because in the callback methods for the Retrofit request, I have to provide also the model class to which the JSON data maps. And I did not know which one to choose.
What is the normal programming approach in such a case?

How to parse a JSON using GSON, to get JSONObject where it is not parsed as desired for a bad JSON?

The question is that when I am parsing the following JSON using GSON library, I am getting GSON class in the form of POJO, where every key and value has a getter and setter.
See the example of such bad JSON below, as not parsed correctly by GSON library
Now that is not the format I require. Instead, I want a hashmap object in return (Library can return ArrayList then why not TreeHashMap ?). For me, this part of JSON is not parsed by GSON as I desire.
My question is whether I should ask my back-end team to reformat the JSON as in second JSON below, or to try to use GSON library as is but extract that JSONObject programmatically from JSON where the keys are dynamic in nature, and it is uncertain whether there are a couple of such keys there or thousands of them in the JSON that is returned.
See the example of the good JSON format below, converted from the bad JSON I have provided as it can be easily parsed by GSON to the format I desire
For this, either I have to explain a rule to my back-end team:
RULE:
The keys should not be dynamic in nature. If in case the keys are dynamic, a list of searchable keys should also be defined in the same JSON or separate MODEL JSON that should be requested in a call before this JSON is parsed (in a separate Web-Service API response).
Example of bad JSON:
{"Grocery": [
{
"id": 2,
"name": "Kirana Store",
"parent_id": 1,
"category_image": "",
"category_type": "product",
"position": 0,
"front_status": 0,
"slug_url": "daal-pulses",
"created_at": "2016-06-27 06:44:59",
"updated_at": "2018-02-13 04:55:33"
},
{
"id": 3,
"name": "Departmental Store",
"parent_id": 1,
"category_image": "",
"category_type": "product",
"position": 0,
"front_status": 0,
"slug_url": "dry-fruits",
"created_at": "2016-06-27 06:45:12",
"updated_at": "2018-02-13 04:56:01"
}
]}
and there may be thousands of dynamic keys like "Grocery" say like "Stationary", "Hosiery", "Medicines", or so... as categories of products. GSON will make getters for each such dynamic key.
Should be corrected and returned by web-service API as:
{
"Products": [
{
"parent_category": "Grocery",
"items": [
{
"id": 2,
"name": "Kirana Store",
"parent_id": 1,
"category_image": "",
"category_type": "product",
"position": 0,
"front_status": 0,
"slug_url": "daal-pulses",
"created_at": "2016-06-27 06:44:59",
"updated_at": "2018-02-13 04:55:33"
},
{
"id": 3,
"name": "Departmental Store",
"parent_id": 1,
"category_image": "",
"category_type": "product",
"position": 0,
"front_status": 0,
"slug_url": "dry-fruits",
"created_at": "2016-06-27 06:45:12",
"updated_at": "2018-02-13 04:56:01"
}
]
}
]
}
Where there can be thousands of categories as Grocery as described above, and getters for such keys can not be computed at run time. But if these keys are converted to values, represented by a common key each, as in the correction above, then having a common getter for that key "parent_category" makes sense. Now, this is the JSON that GSON can parse to my desired output. But the thing is that our back end team do not co-operate to change anything, because there is a re-work here. If I switch to traditional parsing, there will be a huge re-work at my end as well.
OR I have to find out a way where I can extract the JSONObject from the JSON using GSON so that I can parse it manually.
Hence I need something to save time that will go in this re-work.
After getting JSONObject that is not parsed by GSON as desired:
Getting JSONObject from JSON where it is not parsable by GSON:
Use keySet() of JSONObject to get the keys from JSON, as Set collection. Iterating through the keys in the Set, I am obtaining corresponding values, in the current JSON section.
Please see the example:
Java Code Examples for org.json.JSONObject.keySet()
Now if GSON can not parse such kind of JSON formats, where it gives getters and setters for each key and if the developer has to parse JSON manually, then still there is a chance of saving time, using this solution. But till GSON make amendments as you suggest it should, you have to live with this solution.
What should I have done if I were in GSON development team?:
There should have been another kind of annotation where instead of getting getters and setters, one should be able to demand from the GSON library to return key-value pairs in the form of hash-map or array-list of POJO in the output. This at present is not there.
Happy Coding ;-)

How to parse the BigQuery response in android app?

I am trying to access the database tables from Bigquery in Google developer console. The response is coming in following pattern:
[
{ "f": [
{ "v": "value1" },
{ "v": "value2" }
]
},
{ "f": [
{ "v": "value1" },
{ "v": "value2" }
]
}
]
It is long process to parse this and map to pojo class. So is there any other ways to do it ?
Using a JSON library would be your best bet... it at least takes away the headache of raw string parsing. As for pulling the items out, you'll still need to define a POJO to encapsulate the data if you want to use it easily.
Check out GSON
Another one that's easy to use is the standard JSON library, but it is not as efficient.

How to create a dynamic JSON array based on parse.com database

I'm looking for a way to create a JSON dynamic array that looks like this: {
"id": 1,
"name": "National Geographic Channel",
"image": "http://api.androidhive.info/feed/img/cosmos.jpg",
"status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
"profilePic": "http://api.androidhive.info/feed/img/nat.jpg",
"timeStamp": "1403375851930",
"url": null
},
This needs to be generated in the cloud of Parse.com, and has to be based on Parse database then it needs to return a JSON array link that contains JSON arrays so I could be able later to use it on my Android application
If this method is not the best one to work with, could you please provide a better one.
I'm still a newbie in App developpement. Any help would be really appriciated.
Thanks.
https://parse.com/docs/js/api/classes/Parse.Query.html#methods_toJSON
I think your use of the term "dynamic" is confusing... nevertheless I think I understand. From what I can gather you're using Parse.com JavaScript Core SDK, you've created a Class, you want to pull from the object and convert it to JSON format (if so, see my example below).
or use my method...
Parse.initialize("appId", "javascriptKey", "masterKey");
var Blog = Parse.Object.extend("Blog");
var Query = new Parse.Query(Blog);
Query.find({
success: function(parseData) {
var dataString = JSON.stringify(parseData);
var jsonData = JSON.parse(dataString);
// now use jsonData
console.log(dataString);
console.log(jsonData);
},
error: function(parseData, error) {
console.log("Unable to query the Parse object");
}
});

Categories

Resources