json android: parsing json - android

I have a json :
[ {user:"John",s:"Ldh",e:"usa"},{user:"Paul",s:"bukit panjang ",e:"FedExForum - Memphis"},{user:"ross",s:"bukit panjang ",e:"FedExForum - Memphis "}]
I am parsing this with the following code to retrieve all the values of "user" ..
public class ListViewAndroidActivity extends ListActivity {
private String newString, user;
ArrayList<String> results = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TestServiceActivity test = new TestServiceActivity(); //This returns json from the server
newString = test.readPooledFeed(); // returned json in string format
JSONArray rootArray = new JSONArray(newString);
int len = rootArray.length();
for(int i = 0; i < len; ++i) {
JSONObject obj = rootArray.getJSONObject(i);
user = obj.optString("user");
results.add(user);
}
}
This gives me no error.. but nothing is shown on the screen .. kindly help!

optString : Get an optional string associated with a key.
I don't see the key u in your JSON object, shouldn't it be user = obj.optString("user");

JSON formatting
Your JSON data is not valid, it's valid as javascript, but not as JSON.
All properties should be quoted in JSON:
[
{ "user": "John", "s": "Ldh", "e": "usa"},
{ "user":"Paul", "s":"bukit panjang ", "e": "FedExForum - Memphis" },
{ "user": "ross", "s":"bukit panjang ", "e":"FedExForum - Memphis "}
]
Indentation is not needed, I just did it to make it clearer.
Missing field
Your parser seems to ignore that your input data is invalid. Other problem could be as others mentioned you're requesting the u property at user = obj.optString("u"); which does not exists.

Related

Parsing JSON array into objects array

I'm tried to parse some json array (with string and two-dimensional array) into objects array, but the solutions I found do not work (or I was looking bad).
Please, help me with the code to get an array of objects.
I found working method for Java (I tried it in Eclipse) this,
but I want it for Android (in Android Studio)
My json file:
[
{
"someString": "First string",
"someTwoDimArray":
[
["First_firstElement", "First_secondElement"],
[true, false]
]
},
{
"someString": "Second string",
"someTwoDimArray":
[
["Second_firstElement", "Second_secondElement"],
[true, true]
]
}
]
I have java class:
public class someClass {
String someString;
Object[][] someTwoDimArray;
}
What I need: (To process the data in the code later)
someClass[] someClasses = /* ??? */
Try something like this:
JSONArray jsonarray = new JSONArray(jsonStr);
int L = yourArrayWithJSON.length();
first = new String[L];
second = new String[L];
third = new String[L];
for (int i = 0; i < L; i++) {
JSONObject point = vpn.getJSONObject(i);
first[i] = point.getString("first");
second[i] = point.getString("second");
third[i] = point.getString("third");
String url = jsonobject.getString("url");
}
Ask, if you have any questions

Trying to parse a jsonarray within a jsonarray

I am parsing some json in an app and I have come across arrays that sometimes have information in it:
{
"output": [
{
"id": "1521",
"name": "Apples",
}
]
}
and sometimes has nothing. e.g
{
"output": [
[]
]
}
I was parsing it by
JSONArray output = c.getJSONArray("output");
int outputLength = output.length();
for (int q = 0; q < outputLength; q++)
{
JSONObject d = outputs.getJSONObject(q);
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
but when it gets to the empty array it crashes.
I get the following error then:
01-19 01:08:00.237: W/System.err(17627): org.json.JSONException: Value [] at 0 of type org.json.JSONArray cannot be converted to JSONObject
it crashes because it's trying to convert the jsonarray into an object and you can't do that so I tried getting the first array in output with:
JSONArray add = output.getJSONArray(0);
but that will crash as well because in the first output it's an object in it and not an array.
I don't have access or control over the json feed and I'm stuck at the moment as to how to parse the result.
The real answer is: "Fix whatever is generating that horrible JSON".
If that's not an option you're going to have to figure out exactly what you have before trying to access it. The JSONArray.optJSONObject() method can help with this; it returns null if the specified index doesn't contain a JSONObject:
JSONArray output = c.getJSONArray("output");
for (int q = 0; q < outputLength; q++)
{
JSONObject d = output.optJSONObject(q);
if (d != null)
{
id[q] = d.getInt("id");
name[q] = d.getString("name");
}
}
Because you're parsing everything in the enclosing JSONArray as aJSONObject, all the entries would have to be formatted that way. For that to work, your source string would have to look like this:
[
{
"output": [
{
"id": "1521",
"name": "Apples"
}
]
},
{
"output": [
[]
]
}
]
Everything in the top-levelJSONArray is now a JSONObject and can be parsed accordingly. What's inside of those objects is your business (empty arrays are OK). A good resource for checking if a given JSON string is valid is this website.

Android code For Following JSON Pattern

Want Android Code For Following JSON Format...Bit Confused How to fetch value of array For Following Pattern..
{
"params": [
{
"answer_data_all": [
{
"id": "5",
"question_id": "14"
}
],
"form_data_all": [
{
"id": "1",
"name": "form 1"
}
]
}
]
}
You just have some nested JSONArray and JSONObject. Assuming you have this response in string format all you have to do is create JSONObject from that string and then extract what you need. As someone mentioned [ ] encloses JSONArray while { } encloses JSONObject
JSONObject mainObject = new JSONObject(stringResponse);
JSONArray params = mainObject.getJSONArray("params"); //title of what you want
JSONObject paramsObject = params.getJSONObject(0);
JSONArray answerData = paramsObject.getJSONArray("answer_data_all");
JSONArray formData = paramsObject.getJSONArray("form_data_all");
String id = formData.getJSONObject(0).getString("id");
You should be able to extract all the values doing something like this. Although I will say I think the formatting is odd. You're using single member arrays that just contain other objects. It would make much more sense to either use one array to hold all the object or just separate JSONObject. It makes it much easier to read and easier to parse.
Parsing a JSON is fairly simple. You could use GSON library by Google for example. Below is an example I wrote for your object/model:
class MyObject{
ArrayList<Params> params;
class Params {
ArrayList<AnswerData> answer_data_all;
ArrayList<FormData> form_data_all;
class AnswerData {
String id;
String question_id;
}
class FormData {
String id;
String name;
}
}
}
And then get an instance of your object with:
MyObject myObject = (MyObject) (new Gson()).toJson("..json..", MyObject.class);
JSONArray feed = feedObject.getJSONArray("params");
for(int i = 0; i<feed.length(); i++){
JSONArray tf = feed.getJSONArray(i);
for (int j = 0; j < tf.length(); j++) {
JSONObject hy = tf.getJSONObject(j);
String idt = hy.getString("id");
String name = hy.getString("name");
}
}
**NOTE: the 'feedObject' variable is the JSONObject you are working with..Although this your type of JSON feed is kinda mixed in terms of string names and all but this should do for now..

Parse a JSON object value (an Array), not the object

I'm developing an Android application that connects with Facebook using Springframework Android rest client.
With this URL:
https://graph.facebook.com/me/friends?access_token=AUTH_TOKEN
Facebook API returns:
{
"data": [
{
"name": "Friend1",
"id": "123456"
}
]
}
I want to parse the data[] values, as an array:
[
{
"name": "Friend1",
"id": "123456"
}
]
And get a FacebookFriend[].
How can I do it with GSON?
First, you'd need a FacebookFriend class (using public fields and no getters for simplicity):
public class FacebookFriend {
public String name;
public String id;
}
If you created a wrapper class such as:
public class JsonResponse {
public List<FacebookFriend> data;
}
Life becomes far simpler as you can simply do:
JsonResponse resp = new Gson().fromJson(myJsonString, JsonResponse.class);
And be done with it.
If you don't want to create an enclosing class with a data field, you'd use Gson to parse the JSON, then extract the array:
JsonParser p = new JsonParser();
JsonElement e = p.parse(myJsonString);
JsonObject obj = e.getAsJsonObject();
JsonArray ja = obj.get("data").getAsJsonArray();
(You can obviously chain all those methods, but I left them explicit for this demonstration)
Now you can use Gson to map directly to your class.
FacebookFriend[] friendArray = new Gson().fromJson(ja, FacebookFriend[].class);
That said, honestly it's better to use a Collection instead:
Type type = new TypeToken<Collection<FacebookFriend>>(){}.getType();
Collection<FacebookFriend> friendCollection = new Gson().fromJson(ja, type);
It seems, your array contain object.
you can parse it in following way.
JsonArray array = jsonObj.get("data").getAsJsonArray();
String[] friendList = new String[array.size()];
// or if you want JsonArray then
JsonArray friendArray = new JsonArray();
for(int i=0 ; i<array.size(); i++){
JsonObject obj = array.get(i).getAsJsonObject();
String name = obj.get("name").getAsString();
friendList[i] = name;
// or if you want JSONArray use it.
friendArray.add(new JsonPrimitive(name));
}

How to parse JSON without title object in Android?

I've a json output which returns something like this :
[
{
"title":"facebook",
"description":"social networking website",
"url":"http://www.facebook.com"
},
{
"title":"WoW",
"description":"game",
"url":"http://us.battle.net/wow/"
},
{
"title":"google",
"description":"search engine",
"url":"http://www.google.com"
}
]
I am familiar with parsing json having the title object, but i've no clue about how to parse the above json as it is missing the title object. Can you please provide me with some hints/examples so i can check them and work on parsing the above code?
Note : I've checked a similar example here but it doesn't have a satisfactory solution.
Your JSON is an array of objects.
The whole idea around Gson (and other JSON serialization/deserialization) libraries is that you wind up with your own POJOs in the end.
Here's how to create a POJO that represents the object contained in the array and get a List of them from that JSON:
public class App
{
public static void main( String[] args )
{
String json = "[{\"title\":\"facebook\",\"description\":\"social networking website\"," +
"\"url\":\"http://www.facebook.com\"},{\"title\":\"WoW\",\"description\":\"game\"," +
"\"url\":\"http://us.battle.net/wow/\"},{\"title\":\"google\",\"description\":\"search engine\"," +
"\"url\":\"http://www.google.com\"}]";
// The next 3 lines are all that is required to parse your JSON
// into a List of your POJO
Gson gson = new Gson();
Type type = new TypeToken<List<WebsiteInfo>>(){}.getType();
List<WebsiteInfo> list = gson.fromJson(json, type);
// Show that you have the contents as expected.
for (WebsiteInfo i : list)
{
System.out.println(i.title + " : " + i.description);
}
}
}
// Simple POJO just for demonstration. Normally
// these would be private with getters/setters
class WebsiteInfo
{
String title;
String description;
String url;
}
Output:
facebook : social networking website
WoW : game
google : search engine
Edit to add: Because the JSON is an array of things, the use of the TypeToken is required to get to a List because generics are involved. You could actually do the following without it:
WebsiteInfo[] array = new Gson().fromJson(json, WebsiteInfo[].class);
You now have an array of your WebsiteInfo objects from one line of code. That being said, using a generic Collection or List as demonstrated is far more flexible and generally recommended.
You can read more about this in the Gson users guide
JSONArray jsonArr = new JSONArray(jsonResponse);
for(int i=0;i<jsonArr.length();i++){
JSONObject e = jsonArr.getJSONObject(i);
String title = e.getString("title");
}
use JSONObject.has(String name) to check an key name exist in current json or not for example
JSONArray jsonArray = new JSONArray("json String");
for(int i = 0 ; i < jsonArray.length() ; i++) {
JSONObject jsonobj = jsonArray.getJSONObject(i);
String title ="";
if(jsonobj.has("title")){ // check if title exist in JSONObject
String title = jsonobj.getString("title"); // get title
}
else{
title="default value here";
}
}
JSONArray array = new JSONArray(yourJson);
for(int i = 0 ; i < array.lengh(); i++) {
JSONObject product = (JSONObject) array.get(i);
.....
}

Categories

Resources