Parsing JSON through Gson method fromJson - android

I am parsing an API through
ArrayList<Spot> spots = Gson.fromJson(response , new TypeToken<Arraylist<Spot>>(){}.getType())
My response is perfectly fine, but when I see the response through Gson.toJson(spots). It shows me empty objects, means it have parsed the first field of each object in the API but internals fields of each object is not parsed.
I receive null values if I access the internal fields which is obvious . Can any one let me know where the problem lies, why its not parsing any internal field? .

Maybe you have to use List instead of ArrayList.
When you create your json use:
List<Spot> spots = new ArrayList<Spot>();
gson...
And when you parse the response use:
List<Spot> spots = Gson.fromJson(response , new TypeToken<List<Spot>>(){}.getType());
If that does not work, please show your json and the Spot class.

Related

Python json/list to dictionary cast not working

I'm currently deveolping an Android application that has Django framework as it's server side.
When i'm posting a data of a new user to my database i am POSTing a multipart request that has a user part inside.
The user for some reason is represented as a list but when i take it out of the request.data['user'] it's a str instance (Yea i dont know why...)
When i fetch that str i started working on it with json package.
I looked up on the internet (to many places..) how to convert a string in json format to a dictionary.
What i found is that when you use the json.loads command it doesn't give a dict back but a str instance :)
This is the code on my server side when i enter the create function of the ModelViewSet that handles the creation of the user.
userJson = request.data['user']
userJson = json.dumps(userJson)
userJson = json.loads(userJson)
What i tried to do is to make a string of my own in JSON format and that called the json.loads() command which gave me the dict object..
There seems to be a problem with processing the str from the http request of django rest framework for some reason or there's something else i am not seeing.
I tried the following links -
Converting JSON String to Dictionary Not List
http://docs.python-guide.org/en/latest/scenarios/json/
Didn't worked also..
Now, i tried accessing the str i got from json.loads() like a dictionary in this way.
id = userJson['id']
Now lets say maybe i passed a wrong json format to the loads function, it should have thrown an exception..
The code above (getting the id) raised an exception of 'String indices must be integer' - it doesn't convert it to dict! LOL xD
Good note worth mentioning - I'm trying to convert the json to a dictionary so i could access it like this - dictObject['id']
Well i would really appreciate every help!
Thanks :)
For some reason , when i did this commands-
userJson = request.data['user']
userJson = json.loads(userJson)
userJson = json.loads(userJson)
What i got to have inside the userJson after the second json.loads(userJson) I got the actual dict object to the userJson member.
Appearently it is a bug.
21 January - another update, I truly was doing double Json encoding on the Android application so that was the reason for double json. loads()

Display of json parser in tabular form in android app

I am new to Android and I got an assignment where I have to use JSON parser to parse the link and display the content in tabular form and its table field. When clicked, it should open some sections. Please, if anyone knows any kind of tutorial on how to do it, it would be really great. Thank you.
You can use gson to parse the incoming data into POJO. It will be as simple as writing a class that matches your JSON data format.
or just just the GSON framework from google
you will need to create a Pojo(or Bean) with basic constructor and fileds matching the name of the json String.
something like:
Gson gson = new Gson();
gson.fromJson(jsonProvider, new TypeToken<Contact>(){
}.getType()
);
in this case the POJO is named Contact. After that u have an object filled with ur json data that u can use to do what ever u want...
hope this helps

Android JSON fetching - No value for (value) eventhough the value exists

I have a valid json link, and I want to fetch data from it.
This is my code, for fetching data:
try {
JSONObject topicsObject = new JSONObject(getTopicsJSON);
JSONArray topics = topicsObject.getJSONArray("Topics");
for (int i = 0; i<topics.length();i++){
SuperTrenerTopic stt = new SuperTrenerTopic();
JSONObject sub_topic = topics.getJSONObject(i);
JSONObject topic = sub_topic.getJSONObject("Topic");
...
}
On the last line of code, I get ann error saying org.json.JSONException: No value for Topic.
Following screenshot shows that it is not correct, as I Log-ed the recieved JSON, and you can clearly see that in fact, there IS a "Topic" object out there:
First Log represents the first part of an entire Json responce, and the second one is the Topic object itself.
Here is another screenshot of the JSON format i took from my browser:
You can notice that "Topic" and "meta" objects are on the same hierarchy level.
I fetch "meta" object with no problem whatsoever, using the same code I would use for fetching 'Topics", but for some reason, fetching "Topics" doesn't work out.
here is the code I successfully use to fetch "meta' object:
JSONObject meta = sub_topic.getJSONObject("meta");
What could be the cause of this?
Is there something realy obvious that I'm missing out?

Accessing an object from JSON in Android

I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.

json parsing in android of web data

I have to parse this json data. The data begins with [ and ends with ]
How can we parse such json data? json data usually starts with {..[..]..}
Just create a JSONArray from your input. There is even a constructor taking a String as parameter. So, basicly you need to do something like this:
String input = .. //read your input
JSONArray arr = new JSONArray(input);
//work with the array as usual..
take result data as a JSONArray and not a JSONObject.
It depends on how you parse the data. Built in json or google json(gson) etc.
But normally you dont have to care about that it starts with square bracket.
Show me what the json array/object look like and I can give you an example.

Categories

Resources