how to read attribute value in json using android - android

I want to read json attribute value, my json format like this
{"content":{"#attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}},
I want to read total_record's value from json attributes. How can I read ? Please help me
Thanks
John Rick

First of all check your JSON String.Change it to
{"content":{"#attributes" : { "start_limit" :"x","end_limit" : "x","total_records" : "x"}},"item":[{"category":"x","distance':"x"}]}} from
{"content":{"#attributes" : { "start_limit" : "x","end_limit" : "x","total_records" : "x"},"item":[{"category":"x","distance":"x"}]}}
In which you left one closing curly brace before "item".
Now below is the code to get value of "total_records"
String jsonString = "{'content':{'#attributes' : { 'start_limit' :'x','end_limit' : 'x','total_records' : 'x'}},'item':[{'category':'x','distance':'x'}]}}";
public String getTotalRecords(String jsonString){
try {
JSONObject mainObject = new JSONObject(jsonString);
JSONObject contentObject = mainObject.getJSONObject("content");
JSONObject attributesObject = contentObject.getJSONObject("#attributes");
String totalRecords = attributesObject.getString("total_records");
Log.i("Total Records", totalRecords);
} catch (JSONException e) {
e.printStackTrace();
}
return totalRecords;
}
Hope you understand the problem.

Simply use JSONObject.
JSONObject obj = new JSONObject(src);
String totalRecs = obj.getString("total_records");
Not 100% sure it works, but it is a good example where to start.

Hope you've already given it a try before asking in SO. If not, here are a few urls (which I googled):
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/ and http://about-android.blogspot.com/2010/03/androind-json-parser.html

Related

Invalid type for ParseObject

Error : java.lang.IllegalArgumentException: invalid type for ParseObject: class org.json.JSONObject
I have moved parse server on "centOS" and also database from parse.com to mangoDB. I'm getting Above error when I make below request from my android app.
Note : I'm using android parse sdk(v1.13.1)
I have tried to add jsonObject as arraylist using addAllUnique() method because I have to store jsonObject as datatype of "array" in parse database.
Below i share my code :
JSONObject jsonObj = new JSONObject();
try {
jsonObj.put("__type", "Pointer");
jsonObj.put("className", className);
jsonObj.put("objectId", objectId);
} catch (JSONException e1) {
e1.printStackTrace();
}
ParseUser user = ParseUser.getCurrentUser();
user.addAllUnique("Keyword",Arrays.asList(jsonObj));
user.saveInBackground();
I have also tried user.addAll() method insted of addAllUnique() but it's also not working.
Please help me to resolve this. Thanks
You can try something like this instead of JSON Object.
List<ParseObject> pointerList = new ArrayList<>();
pointerList.add(ParseObject.createWithoutData("YourClassName", "yourobjectId"));
pointerList.add(ParseObject.createWithoutData("YourClassName", "yourobjectId"));
...
user.addAllUnique("keyWord", pointerList);
user.saveInBackground();
Haven't tested the code yet. But technically, it should work.
Hope this helps :)

A value of a json str sometimes is a String, sometimes is a object, how could i use gson to parse it

Like the title , my json str sometimes like this:
{
"data": {
"changebaby": "no change",
"changemama": {
"mamacontext": "mama is a good mama",
"mamaico": "",
"mamatitle": "mama"
}
}
}
sometimes it like this:
{
"data": {
"changebaby": "no change",
"changemama": "no change"
}
}
as you see,the value of the "changebaby" key and the "changemama" key sometimes is a String, sometimes is a object, how should i parse it by gson? Could anybody help me?
Don't use the android api to parse the json string, need to use the gson lib of google to parse the json string, could anybody help me?
if(jsonObject.optJSONObject("changemama") != null)
{
JSONObject changemama=jsonObject.optJSONObject("changemama");
//Its JSON object, do appropriate operation
}
else if(jsonObject.optString("changemama") != null)
{
//Its string, do appropriate operation
}
if you have more number of possibilities like boolean or int or long, refer this
optJSONObject
Returns the value mapped by name if it exists and is a JSONObject, or
null otherwise.
Or go with the way lawrance has given : Determine whether JSON is a JSONObject or JSONArray
Try with this :
JSONObject changemama=jsonObject.optJSONObject("changemama");
if(changemama== null){
String str=jsonObject.optString("changemama");
}
Try this code.
JSONObject data;
try {
data = jsonObj.getJSONObject("changemama");
// do stuff
} catch (JSONException e) {
data = jsonObj.getString("changemama");
// do stuff
}
try this :
if(obj.has("changemama")){
if(obj.optString("changemama").length() > 0){}
else if(obj.optJSONObject("changemama").length() > 0){}}
To simplyfy android development, we can ask for the backend developers to change the Mobile API.The new API could returen the json string that cann't change the value.The value of all keys cann't sometimes be a string, sometimes a object.

gson handle: Expected BEGIN_OBJECT but was BEGIN_ARRAY

I am using Retrofit and Gson to make API calls. I have a problem with responses from server. For some attributes it is sending empty JSONArray instead of null JSONObject. e.g.:
in normal situation:
{
"pagination": {
"links": {
"next": "http://api.com/nextlink"
}
}
}
but sometimes when the "links" is empty, the server sends me this:
{
"pagination": {
"links": []
}
}
which cause java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY.
I know that I can handle it with using custom JsonDeserializer for object "Pagination" and registerTypeAdapter when creating GsonBuilder.
But my question is: It is possible to handle this cases in general for all responses? I don't have access to API so I cannot change it and I don't know for which attributes I can get empty JSONArray instead of JSONObject that is expected.
Thank you.
You can use JSONTokener to get normal Object after check it with instanceof function, try bellow:
String jsonData = "{...}"; //your json data string
JSONTokener tokener = new JSONTokener(jsonData);
try {
Object parsedObj = tokener.nextValue();
if (parsedObj instanceof JSONObject) {
//do something here
}else if (parsedObj instanceof JSONArray){
//do something here
}
}catch(Exception ex){}
Read more here enter link description here
Try this to check if it is an object or not
yourJson.get("links").isJsonObject()
check these methods
isJsonArray()
isJsonObject()
isJsonNull()

Android Json tag into String

I use this code for reading a tag by a specific URL:
public static String ter(final String PRIVATE) {
JsonParser parser = new JsonParser();
try {
Object obj = parser.parse(new FileReader("my url string"));
JSONObject jsonObject = (JSONObject) obj;
String event = (String) jsonObject.get("EVENT");
return event;
} catch (Exception e) {
e.printStackTrace();
}
return PRIVATE;
}
Then I set my subTitle with PRIVATE in this way:
getActionBar().setSubtitle("test"+ter(PRIVATE));
But when I run my app, in subTitle I read only text "test" with text "null" and it doesn't read the tag of JSON. Anyone has any idea? Is my code wrong?
Because you may have not initializes your variable therefore it is pointing towards null values....
When ever we create object,either by calling that method or by initializing variable at declaration, we can avoid null pointer exception...
Please refer to this POST
You are setting the subtitle to PRIVATE, but if your parsing succeeds, you're returningevent. You're also sending PRIVATE into this function, for some reason.

use textview to display message when json response is null

In my JSON response I am get nothing in value and at that I want to print message using textview I am trying but its not showing nothing,can any one help?the response is looks like this
{"name":"Patel Monali","age":24,"location":"","mother_tounge":"","occupation":"","income":"","height":"","cast":"","marital_status":"","religion":"","gotra":"","manglik":"","rashi":"","education":"","eating":"","drink":"","smoke":"","about_me":"","profile_pic":"Imaege","user_status":"Accept","interest_id":1288}
and here is the code:
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String user_name = jsonObj.getString(USER_NAME);
String user_age = jsonObj.getString(USER_AGE);
...............
final TextView uname = (TextView)findViewById(R.id.namedetail);
final TextView fdetail = (TextView)findViewById(R.id.firstdetail);
..............
uname.setText(user_name);
fdetail.setText(user_age+" years");
androidAQuery.id(ucover).image(user_pro, true, true);
}catch (JSONException e)
{
e.printStackTrace();
}
If I understand your question correctly here is what you need
if(user_name==null)
{
uname.setText("not willing to specify");
}
else
{
uname.setText(user_name);
}
If you need something more please update your question or tell me in comments.
.
Hope it help
All you have to do is check if the received string is null.
for example:
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation.length==0){
user_occupation="not willing to specify";//set your message here
}
OR
String user_occupation = jsonObj.getString(USER_OCCU);
if(user_occupation==null){
user_occupation="not willing to specify";//set your message here
}

Categories

Resources