Parsing JSON data from an XML web service in Android - android

I have an XML web service. I want to parse this XML and I want to store in an separate textviews. The following is an XML content, and I have finished getting it in a String variable.
{
"30_year_rate": 4.25,
"30_year_pi": 196.78,
"30_year_apr": 4.375,
"20_year_rate": 4.375,
"20_year_pi": 250.37,
"20_year_apr": 4.5,
"15_year_rate": 3.75,
"15_year_pi": 290.89,
"15_year_apr": 3.875,
"10_year_rate": 3.625,
"10_year_pi": 397.89,
"10_year_apr": 3.75,
"5_year_arm": 2.75,
"5_year_pi": 163.3,
"5_year_apr": 2.875,
"7_year_arm": 3,
"7_year_pi": 168.64,
"7_year_apr": 3.125,
"3_year_arm": 4,
"3_year_pi": 190.97,
"3_year_apr": 4.125,
"5_year_io_arm": "N/A",
"5_year_io_pi": "N/A",
"5_year_io_apr": "N/A",
"QuoteID": 1449,
"Licensed": "N"
}
How can I parse this data? I want to convert it to a JSON object and retrieve it, or any other reasonable approach.

If what you're getting back from the webservice is the string above, then you already have a JSON string. To create an object that can retrieve information from it, use something like JSONObject.
JSONObject object = new JSONObject(your_string_variable);
double thirtyYearRate = object.getDouble("30_year_rate");
String licensed = object.getString("Licensed");
etc.
You might (will) run into some issues where you try to pull a double from a JSON field that contains a string; i.e., the "N/A" fields above. You'll likely have to pull them out as strings and then try to parse doubles from them, and if the parsing throws an exception, you'll know it's a string.
Alternately, you could look into JSON binding with something like Jackson, which apparently runs on Android.

To parse JSON, you could use the built in JSONObject org.json Or Json-lib if you use an old version of android.
To parse XML, use XMLPullParser. A sample can be found here: Parsing XML Data

Related

JSON Conversation

I have a JSON which is returned from a Web Service Developed in PHP but I need help to converting this JSON to JSONArray in Android
{"Name":"John","Contact":"3331234567"}{"Name":"Doe","Contact":"3017654321"}{"Name":"Smith","Contact":"3001234765"}
How can i convert this String returned from URL to JSONArray
Thank you Guys for giving me an idea to fix this problem. I have figured it out bu conceding a string e.g: "n" while writing response on my web service now i can split this on my Android App.
I'd suggest to return it from the web service as a standard JSON Array, which means:
[{"Name":"John","Contact":"3331234567"},{"Name":"Doe","Contact":"3017654321"},{"Name":"Smith","Contact":"3001234765"}]
In this case you can parse it with any common json parser easily (gson, org.json, any other).
Returning it as you do it now produces invalid JSON - just put it to any online JSON validator and it will complain about this.
1. I suggested you to create json file in standard mode
like this:
{
"USER":[ {
"Name":"John",
"Contact":"3331234567"
}
{
"Name":"Doe",
"Contact":"3017654321"
}
{
"Name":"Smith",
"Contact":"3001234765"
}]
}
if you have not any field more , you can remove "USER":
2. You should use json parser library like GSON
**3.**use "pojo" site for create json model in java like http://www.jsonschema2pojo.org/

How to display a JSON file in a TextView

I'm very new to Android and having a lot of trouble understanding JSON. I have a separate JSON file with my values written out but no idea how to actually display those strings in an Android app.
Any comprehensive tutorials or basic-level explanations are very welcome. Thanks!
First of all try to understand AsyncTask also. It allows the user to perform a long background operations and to show the results back to the user in the MainUI Thread. You can perform JSON parsing and get values which is stored inside the JSON file via AsyncTask.
JSON is very light, easy to understand and it's the best alternative to XML. To parse your JSON file you need to know about JSONArray and JSONObject. In a JSON file , square bracket [ represents a JSON array and curly braces { represent the JSON objects. JSON is structured with Key and Value pairs. Get your string values with getString("key");and then just display it into TextView
JSONArray - It contains many JSON Objects.
JSONObjects - It contains key and value pairs.
[ -> It represents the JSON Array
{ -> It represents the JSON Object
Two methods getJSONArray() and getJSONObject() are mainly used in the JSON to represent the json node.
Get your JSON Array node.
JSONArray booksArray = jsonObj.getJSONArray("books");
JSON Code :
{
"books": [ //JSON array
{ //represents JSON Object
"id":"440", //Key and Value pair
"edition": "Fourth",
"language": "Java",
},
{
"id":"407",
"edition": "second",
"language": "Python",
}
]
}
Above code has one JSON Object(books) and one JSON Array it holds two json objects. See this for JSON Parsing in Android.
You can also upload your JSON file for free pastebin and view your JSON file as tree structure with JsonViewer
NOTICE : Comments are not officially supported in JSON. So I just added comments like in JAVA.

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()

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