Extract JSON data from Json Feed - android

I am trying to extract data using json feed. But I get NullPointerexception due to there is no JSONObject.
I am trying to extract following data.
{"postcode":"HA0 4TL","geo": {"lat":51.55135528090932,"lng":-0.29906534560684617,"easting":518029.0,"northing":184978.0,"geohash":"http://geohash.org/gcpv30whrm0s"},"administrative":{"council":{"title":"Brent","uri":"http://statistics.data.gov.uk/id/statistical-geography/E09000005","code":"E09000005"},"ward":{"title":"Wembley Central","uri":"http://statistics.data.gov.uk/id/statistical-geography/E05000104","code":"E05000104"},"constituency":{"title":"Brent North","uri":"http://statistics.data.gov.uk/id/statistical-geography/E14000592","code":"E14000592"}}}
I can create JSONObject as follow.
String in;
JSONObject reader = new JSONObject(in);
But how can I get postcode?
Following code returns NullPointerException.
JSONObject postCode = reader.getJSONObject("postcode");

You should use
String postCode = reader.getString("postcode");

Related

Json - how to parse a url in Android

I want to parse json from a url and use the json data with a listview.
I also want to only list the score and the name, but I have no idea how. Thanks.
{
"level":[
{
"id":1,
"server":[
{"score":33,"name":"Car"},
{"score":72,"name":"Bus"},
]
}
]
}
Do you know how to retrieve the data?
After you retrieve the data, parsing it is very simple. To get each individual item with its attributes I would use the following code:
String responseFromUrl;
JSONObject JSONResponse = new JSONObject(responseFromURL);
JSONArray level = JSONResponse.getJSONArray("level");
//The following loop goes through each object in "level". This is nessecary if there are multiple objects in "level".
for(int i=0; i<level.length(); i++){
JSONObject object = level.get(i);
int id = object.getInteger("id");
JSONArray server = object.getJSONArray("server");
//This second loop gets the score and name for each object in "server"
for(int j=0; j<server.length(); j++){
JSONObject serverObject = server.get(i);
int score = serverObject.getInteger("score");
String name = serverObject.getString("name");
}
}
Obviously replace "responseFromUrl" with the JSON response from the url in string format. If you don't know why I used JSONObject, JSONArray, String, Integer, etc., or are just confused about this, Udacity has a good course for making http connections and parsing JSON responses from APIs.
Link to Udacity Course
You can use the gson library to convert json to an java object
Download the latest jar and import into your project, currently you can download the latest at this link:
https://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.1/gson-2.8.1.jar
After, this will help you:
https://stackoverflow.com/a/23071080/4508758
Hugs!

How to extract objects from json

I have a scenario where I need only 1 objects out of the entire json.
{"id":"1","first_name":"Steve","last_name":"Holt","user_type":"Teacher","user_key_area":"Math"}
In above I want to extract user_type.
How will I do?
You can use Google GSON to parse the json response and map it to the model directly . Here is the tutorial for the same TUTORIAL
Use this to extract the user_type from the json, pass the your json response in place of response variable.
JsonObject object =new JsonObject(response);
String user_type = object.getString("user_type");
You are getting this json in response you can get 1 object like this:
String value = response.getString("Key Name");
Get Response and that create JsonObject
JsonObject jsonObject =new JsonObject(res);
Create String object and pass string parameter "user_type"
String userType = jsonObject.getString("user_type");

In which form the data of facebook graph api me/home should be stored?

I'm getting some user data with API /me/home. I want to ask that in which form shall I store the result- in JSONArray or JSONObject?
Please tell me the method to store data. I am using following procedure to get user data i am storing it in string now.
if (fb.isSessionValid()) {
button.setImageResource(R.drawable.logout_button);
pic.setVisibility(ImageView.VISIBLE);
JSONObject obj=null;
JSONArray feed = null;
URL img_url = null;
try {
String JSONUser = fb.request("me");
obj = Util.parseJson(JSONUser);
String id = obj.optString("id");
String name = obj.optString("name");
String newsfeed=fb.request("me/home");
Please help me.
The result of /me/home will be of form-
{
"data":
[
.. .. ..
]
}
So, take the result in a JSONObject, then for the key data save the result to a JSONArray and then use the data.
You can always check the results of the Graph API in Graph API Explorer.

how to generate JsonStringer for this Json Data Format?

hello i have a JSON data format can anyone please help me to make dynamic JSONStringer object for this String
{"Text":"Hello Simple Text",
"Files":[{"ContentType":"image/png",
"Content":"iVBORw0KGgoAAAANSUhEUgAAAR8AAACMCAIAAADKsDpDAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAAB3RJTUUH2wYWDzIB3zSYdQAAAAd0RVh0QXV0aG9yAKmuzEgAAAAMdEVYdERlc2NyaXB0aW9uABMJISMAAAAKdEVYdENvcHlyaWdodACsD8w6AAAADnRFWHRDcmVhdGlvbiB0aW1lADX3DwkAAAAJdEVYdFNvZnR3YXJlAF1w/zoAAAALdEVYdERpc2NsYWltZXIAt8C0jwAAAAh0RVh0V2FybmluZwDAG+aHAAAAB3RFWHRTb3VyY2UA9f+D6wAAAAh0RVh0Q29tbWVudAD2zJa/AAAABnRFWHRUaXRsZQCo7tInAAABAElEQVR4nO2de1zUVf7/3+dzmwsMoCgDXgARBO/"}],
"AuthToken":"XkWQRd65+H+iPtlOoAEYAR0jrzB1o3UV"}
i have used
jsonstr = new JSONStringer().object().key("Text")
.value(msg).key("Files").array().object().key(
"ContentType").value("image/png").key(
"Content").value(enimg)
.endObject().endArray().key("AuthToken").value(token)
.endObject();
but the server is giving me fault message in return, not accepting the data.
actually i was doing the right thing..everything was OK..
the problem was with org.json package it was not accurate with Base64 string
i switched to another library and all worked..
https://stackoverflow.com/questions/338586/a-better-java-json-library
see the above question for another json libraries
that was problem with org.json
i switched to another..and all it works
nesting too deep in JSON... should I switch to XML?
This is a way to do what you want:
// Creating root JSONObject
JSONObject json = new JSONObject();
// Put in it a String field
json.put("Text", "Hello sample");
// Creating a JSONArray
JSONArray arr = new JSONArray();
//Creating the element to populate the array
JSONObject element = new JSONObject();
element.put("ContentType","image/png");
element.put("Content","iVBORw0K...gDXgARBO/");
// Put it in the array
arr.put(element);
// Put the array and other fileds in the root JSONObject
json.put("Files", arr);
json.put("AuthToken", "XkWQ...o3UV");
// Get the JSON String
String s = json.toString();
// Get formatted and indented JSON String
String s2 = json.toString(4);
// 4 is the number of spaces to indent the string
You can use JSONObject class for this purpose
http://developer.android.com/reference/org/json/JSONObject.html

Trouble with Android JSONObject from Grails webservice

Okay I am quering data from a Grails webservice that returns JSON. The JSON when viewed with the JSONViewer app parses fine. When I take that same string and use JSONObject(string) in my Android app I get "value of String cannot be converted to JSONObject."
Here's my JSON string
[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]
Now the JSON is comes from the standard JSON conversion of a SQL data using render from the groovy file through the import grails.converters.JSON.
... //(call to render JSON in the groovy file)
def a
a = Table.findAll("from someTable as st where st.id=" params.id)
render a as JSON
...
So I am not sure what I doing wrong and why the JSON looks a little off to me. (still new to JSON)
In json if you see "[]" means its a json array and if you see "{}" it is an json object. Both of then can have the other nested inside then.
In your case the string the starts with json array.
So try something like the following
String str = "[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]";
JSONArray jsonArray = new JSONArray(str);
jsonArray = jsonArray.getJSONArray(0);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String class = jsonObject.getString("class"); // class will value "mygrails.TopTen"
Try to create an JSONArray from the String instead of JSONObject. I didn't test this but that should do the trick: you have two nested arrays that contain then actual data.
Check out your JSON online with http://jsonformat.com/
http://www.freeformatter.com/json-formatter.html
JSON Viewer
http://jsonviewer.stack.hu/
Paste your text in there and you can see what you should parse:

Categories

Resources