how to parse this json obj android - android

i m facing prob in parsing this obj
{
"id": 1909,
"permalink": "http:some url",
"title": "Voting begins for third phase of Bihar polls",
"excerpt": "some data.",
"date": "October 27, 2010 21:23",
"tags": [
"bihar",
"india-politics"
]
}
pls tell how to read tags value how to read value of tags

Lets say "jsonString" is equal to that example string
JSONObject json = new JSONObject(jsonString);
int id = json.getInt("id");
String permalink = json.getString("permalink");
JSONArray tags = json.getJSONArray("tags");
String firstTag = tags.getString(0);
You need to catch JSONExceptions and optionally check json.has("someproperty") before grabbing data.

u can use
Gson gson = new Gson();
List mylist = gson.fromJson(json, listtype);
u have to import gson jar which u can google it

In android Json classes are available, so no need to go elsewhere...
Step 1 : Init Json object with source string
JSONObject jObject = new JSONObject(srcString);
Step 2 : Init parent tag with another json object
if parent tag contains array the take JosnArray else JsonObject, in ur case suppose obj is parent tag then
JSONObject data = jObject.getJSONObject("obj");
Step 3 :
Now get String values
data.getString("id");
Or if array then
JSONArray dataArray = data.getJSONArray("tags");
JSONObject menuObject =dataArray.getJSONObject(0);
String firstvalue= menuObject.getString("first");

Use the JSONObject and its methods as Ian says above, however if you don't want your app to throw exceptions if any of the values are missing you can also use the 'opt' (Optional) methods, e.g.
JSONObject json = new JSONObject(jsonString);
String permalink = json.optString("permalink","");
Rather than throw an exception if 'permalink' is not found, it will return the second parameter, in this case an empty string.

Related

How to use single word as JSON data in android?

I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.
My Code is -
JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.
It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.
URL just gives a word like - done that's it not even " or : { nothing
Then simply use the String variable s , don't convert it into json
plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception
try{
// exception will be thrown in case of invalid json
JSONObject jsonObject = new JSONObject(s);
}
catch(JSONException e){
// s containing a single word so use it as it is
}

unterminated character when parsing json in android

I am using the Retrofit package from square to make http request to my server. I get json data from my server that needs to be parsed. The problem I'm having is when the name field has more than one word I get a "Unterminated object at character". What can be the problem.
This works fine
{results=[{id=23.0, name= Canada}]}
This does not
{results=[{id=23.0, name= United States}]}
JSONObject jsonResponse = new JSONObject(data);
JSONArray result = jsonResponse.getJSONArray("results");
for(int i=0; i <result.length();i++ )
{
MyObj obj = new MyObj();
obj.id= result.getJSONObject(i).optString("id").toString();
obj.name=result.getJSONObject(i).optString("name").toString();
p.add(obj);
}
Your input is not valid according to the JSON specs.
It shoud be:
{"results":[{"id":23.0, "name":"United States"}]}
See: http://json.org/

How parse json object and json array together

i have two situation of Json output .
one is data that found and i have a json array and a json object like this:
{"data":"yes"}[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]
other situation is that data not found :
{"data":"no"}
just one json object.
how parse this data in android client for support two situtaion?
First, you should validate your json in http://jsonlint.com/ if you test it you will look that is a wrong json. So, for make it right, in your server your response should look something like this:
{"data":"yes","response":[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
And in that case, in android
JSONObject jsonObj = new JSONObject(response);
if (jsonObj.getString("data").compareTo("yes") == 0) {
JSONArray jsonArray = jsonObj.getJSONArray("response");
//To-Do another code
}
and that's all
Here is a possible case: (you need to fix your json format)
Success -
string resultJSON =
{"success":true,
"data":[
{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},
{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
Failed -
string resultJSON =
{"success":false}
Then
JSONObject jsonRoot = new JSONObject(resultJSON);
bool isSuccess = jsonRoot.getBoolean("success");
if (isSuccess) {
// do the array parser
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonObj = jsonData.getJSONObject(i);
String id = jsonObj.getString("id"); // get the value of id
String desc = jsonObj.getString("desc"); // and so on...
}
}

Which is the best way to parse JSON data in Android?

I have JSON data to parse. The structure is not fixed, and sometimes it comes as a single string and other times as an array.
Currently, we are using the GSON library for parsing JSON, but are facing problems when it comes as an array.
For example:
1. {"msg":"data","c":300,"stat":"k"}
2. {
"msg": [
" {\"id\":2,\"to\":\"83662\",\"from\":\"199878\",\"msg\":\"llll\",\"c\":200,\"ts\":1394536776}"
],
"c": 200,
"stat": "k",
"_ts": 1394536776
}
In the example above, sometimes I get msg as a string and sometimes as an array.
Can anyone help me? If I decide to use JSON parsing, it will be very tedious because I have around 20+ API to parse and each API contains a mininum of 50 fields.
You can use JSONObject and JSONArray classes instead of GSON to work with JSON data
for the first example
String jsonStr = "{\"msg\":\"data\",\"c\":300,\"stat\":\"k\"}";
JSONObject jsonObj = new JSONObject(jsonStr);
String msg = jsonObj.getString("msg");
Integer c = jsonObj.getInteger("c");
String stat = jsonObj.getString("stat");
For the second example
String jsonStr = ... // "your JSON data";
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jsonArr = jsonObj.getJSONArray("msg");
JSONObject arrItem = jsonArr.getJSONObject(0);
//and so on
Also JSONObject class have method opString, opArray which does not throw exception if data you trying to get is not exist or have a wrong type
For example
JSONArray arr = jsonObj.optJSONArray("msg");
JSONObject msg = null;
if (arr != null) {
msg = arr.getJSONObject(0)
} else {
msg = jsonObj.getJSONObject("msg");
}
You can use Google GSON lib for directly parse the json to class object. This is easy and accurate.Okay do one thing both time code is different, if the code is 300 directly parse the json object without GSON. if the code is 200 the use the GSON (Define the similar java class)
String c= json.getString("c");
if(c.equals("300")
String message = status.getString("msg");
There are two ways to parce JSON.
Manually using Android OS JSON Parser Android JSON Parsing And Conversion
Using GSON Library [Library] (https://code.google.com/p/google-gson/downloads/list). This easy to handle if you know all the parameters and models of json response.
Refer the code snippet below to deserialize your json using Google's Gson library without exceptions.
String jsonStr = "your json string ";
Gson gson = new Gson();
JsonObject jsonObj = gson.fromJson (jsonStr, JsonElement.class).getAsJsonObject();
JsonElement elem = jsonObj.get("msg");
if(elem.isJsonArray()) { //**Array**
ArrayList<MyMessage> msgList = gson.fromJson(elem.toString(), new TypeToken<List<MyMessage>>(){}.getType());
} else if(elem.isJsonObject()) { //**Object**
Note note = gson.fromJson(elem.toString(), MyMessage.class);
} else { //**String**
String note = elem.toString();
}
MyMessage class
public class MyMessage {
String to;
String from;
String msg;
int id;
int c;
long ts;
// Setters and Getters
}

JSON Traversing to element using Json webservices in android

I am taking result of a json webservice in JSONObject. While printing this jsonObject it is printing exact result. I got problem at the time of fetching values in this result because i am reading a complex response that is in the form of
{"FoodMenuRS"
:{"Status":"Success",
"TotalResults":2,
"Results":{"Items":
{"Item":[
{"#Id":"6","#Name":"Tea"},
{"#Id":"4","#Name":"Coffee"}
]}}}}
Here i am reading through,
JSONArray jsonArray = json.getJSONArray("Item");
Here i am getting error "No Value for Item"
Where as i got fetched value while calling another service which is simple in format,
{"earthquakes":
[{"eqid":"c0001xgp","magnitude":8.8,"lng":142.369,"src":"us","datetime":"2011-03-11 04:46:23","depth":24.4,"lat":38.322},
{"eqid":"2010xkbv","magnitude":7.5,"lng":91.9379,"src":"us","datetime":"2010-06-12 17:26:50","depth":35,"lat":7.7477}]}
I called it using,
JSONArray earthquakes = json.getJSONArray("earthquakes");
Please help how to fetch this type of Json response. Thanks in advance.
ya it is very complex but i refer you to use Gson library to parse Json as it is parse in structural manner example
check this:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
Done with
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeValue = menuObject.getString("value");
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
String attributeValue = menuObject.getString("value");
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
With every new curley braces call getJSONObjectand for child call getString.
Or you can follow Gson concept to fetch response.

Categories

Resources