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

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");
}
});

Related

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?

Firebase dump json data

I'm no back-end developer. So perspective is always appreciated.
I have written a script which requests from an API and creates this huge JSON file I want to save in firebase, how can I accomplish this? And would it be possible to filter this json with python for example; when I add region=eu in the url this returns the objects which have Europe as region or do I absolutely need to request the entire json file and parse in my code (java android) ?
Since there are a few parts to your question:
You can save JSON to Firebase and the data will be mapped to child locations:
Using PUT, we can write a string, number, boolean, array or any JSON object to our Firebase database...When a JSON object is saved to the database, the object properties are automatically mapped to child locations in a nested fashion.
https://firebase.google.com/docs/database/rest/save-data
And for your next question:
And would it be possible to filter this json with python for example; when I add region=eu in the url this returns the objects which have Europe as region
Looks like you should be able to jimmy something together with Firebase's filters, startAt and endAt:
We can combine startAt and endAt to limit both ends of our query.
https://firebase.google.com/docs/database/rest/retrieve-data#section-rest-filtering
For your example you might do something like this:
curl 'https://yourfirebase.firebaseio.com/yourendpoint.json?orderBy="$REGION_NAME"&startAt="EU"&endAt="EU"&print=pretty'
...or do I absolutely need to request the entire json file and parse in my code (java android) ?
The facts that JSON objects are stored hierarchically in Firebase and that you can filter based on those object values makes me think you do not, in fact, have to request the entire JSON file. However, I don't have personal experience with this particular aspect of Firebase, so give it a shot!
As #ackushiw mentions in the comments, you can also use the equalTo query (https://firebase.google.com/docs/reference/js/firebase.database.Query#equalTo):
curl 'https://yourfirebase.firebaseio.com/yourendpoint.json?orderBy="$REGION_NAME"&equalTo="EU"&print=pretty'
It really depends on how you are structuring your JSON. It's generally recommended to make your JSON tree as shallow as possible since all children are loaded when you have a matching query.
FIREBASE DATA:
{
"-id1": {
"region": "eu" // bear in mind queries are case sensitive
"title": "Foo"
"nested": {
"city": "berlin"
}
},
"-id2": {
"region": "other"
"title": "Bar"
"nested": {
"city": "berlin"
}
},
"-id3": {
"region": "eu"
"title": "Baz"
"nested": {
"city": "paris"
}
}
}
Querying with (using the Android API)
.orderByChild("region").equalTo("eu")
would return "-id1" and "-id3"
with
.orderByChild("nested/city").equalTo("berlin")
would return "-id1" and "-id2"
The REST API Returns Unsorted Results: JSON interpreters do not enforce any ordering on the result set. While orderBy can be used in combination with startAt, endAt, limitToFirst, or limitToLast to return a subset of the data, the returned results will not be sorted. Therefore, it may be necessary to manually sort the results if ordering is important.
If you're using a more complex structure I recommend watching this video
https://www.youtube.com/watch?v=vKqXSZLLnHA
I'd also recommend using the firebase library for Android
https://firebase.google.com/docs/android/setup
And Firebase-UI, It does a lot for you.
https://firebaseopensource.com/projects/firebase/firebaseui-android/

How to parse code from json in android just like we pass text and images?

I am creating a question answer kind of app in android and passing data through json file but i need how to pass a code or syntax in json file which display properly in my android app.
"Question": "what is json?",
"Answer": "Javascript Object Notation",
"Image": "json.png"
//code or syntax
But how to pass a code here?

The Easiest Way To Parse/Read Json

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

Converting Facebook notifications from json

In my app I'm receiving notifications from Facebook using facebook sdk for android. But the data returned by response.toString() method is in json format.
I need to know how can I convert it in simple human readable format so that I can use them to view in a textfield?
This is what I get out of graph explorer.Required string is "title"
{
"id": "10000115768434",
"name": "Nauman Aslam",
"notifications": {
"data": [
{
"id": "notif_10000357346818423_6543370",
"from": {
"name": "Muhammad Asad Iqbal",
"id": "56342467433"
},
"to": {
"name": "Nauman Aslam",
"id": "324545436818423"
},
"created_time": "2014-03-28T20:09:02+0000",
"updated_time": "2014-03-28T20:16:05+0000",
"title": "Muhammad Asad Iqbal and Smat Kazmi also commented on Muhammad Asad Iqbal's photo.",
"link": "http://www.facebook.com/photo.php?fbid=4040070417111&se",
"application": {
"name": "Photos",
"id": "54635732"
},
"unread": 1
},
You will either need to find JSONparser libraries on-line and use them or if you want you can write your own JSONparser class and parse the data in java objects (By the way JSON response is usually human readable its just that it comes as an object or arrays or objects).
if you want to write your own JSONparser class it shouldn't be that hard we can not advise you on where to start until you post the JSONresponse and we see the format of the response.
one things I would say is first check the format of your JSON response. It is very important to know the format because if JSONresponse comes in format of "object of arrays of objects" you must decode it using "JSONObject --> JSONArray ->> JSONObject" otherwise your program will crash. Click here and copy paste your json response on the textbox it will show you the format of it.
If you want to start with basics of JSON decoding Click here and check my answer on stackoverflow its very basic but if you have only started to deal with JSONresponses it might be a good start.
Edit
As per your JSONresponse it starts from curly brackets which means the response is one JSONObject but I do not see the whole JSONresponse and some brackets are missing so my answer might not make sense but you can follow the steps if you understand it
first thing you do is save the response in 'String' object and create a JSONObject and initialise it by passing the response. then you want the the "notifications" object extracted from it so you again create second JSONObject this object will only extract "notifications" object from the string
then you want the JSONArray "data" to be extracted so you define a JSONArray and getJSONArray("data") from you JSONObject.
and thei again you will need JSONObject to only extract "title" object.
to summarise
Create JSONObject and pass the response String to it
Create second JSONObject from it
Create JSONArray and use getJSONArray("___") method on you JSONObject
and finally create last JSONObject inside a for loop if you have more than one notification
and use getString("title") method on that object
Your JSON response is not complete so I might be wrong but you can give it a try.
When you get a response string in json format there are libraries that allows you to turn your string in a dictionary type.
If you want a web site that helps you view a json string in readable by hummans go here Online JSON Viewer.
Paste your code in the first page then go to viewer tab, you'll see the name of the keys and the values.

Categories

Resources