Android - JSON get single value - android

I have a single JSON object like this
"stringData"
with no column names or anything just a single string
I'm confused how to get that value with no column names
edit the following code to get that single value ?
private void showJSON(String response){
String value="";
try {
JSONObject jsonObject = new JSONObject(response);
value = jsonObject. ??????
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("Value:\t"+value);
}

your response is a string but not in json form. so convert this string into jsonObject give JSONException. So. you can do two things 1. first use this string without making jsonobject OR 2. send string in json form from server than convert the string into jsonobject and use.

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
}

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...
}
}

JSON parsing error, android?

I have the following JSON
{"DistributorDealerList":
{[{"Id":2,
"Name":"Distributor1",
"Dealer":
[{"Id":"1",
"Name":"Dealer1"},
{"Id":"2","
Name":"Dealer2"}]},
{"Id":4,"Name":"Distributor2",
"Dealer":
[{"Id":"3",
"Name":"Dealer3"}]}]}
When I am parsing the JSON getting the below exception
org.json.JSONException: Names must be strings, but [{"Name":"Distributor1",
"Dealer":[{"Name":"Dealer1","Id":"1"},{"Name":"Dealer2","Id":"2"}],"Id":2},
{"Name":"Distributor2","Dealer":[{"Name":"Dealer3","Id":"3"}],"Id":4}] is of
type org.json.JSONArray at character 195 of {"DistributorDealerList":
{[{"Id":2,"Name":"Distributor1","Dealer":[{"Id":"1","Name":"Dealer1"},
{"Id":"2","Name":"Dealer2"}]},{"Id":4,"Name":"Distributor2","Dealer":
[{"Id":"3","Name":"Dealer3"}]}]}
HERE is my parsing code:
try {
JSONObject jsonObj = new JSONObject(apiResult);
// Getting JSON Array node
JSONArray contacts = jsonObj
.getJSONArray("DistributorDealerList");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String distId = c.getString("Id");
String distName = c.getString("Name");
JSONObject phone = c.getJSONObject("Dealer");
String distDealerID = phone.getString("Id");
String distDealerName = phone.getString("Name");
}
} catch (JSONException e) {
e.printStackTrace();
}
It says that I must supply the JSON Araay Name. Though I am supplying it but still the exception. What is wrong here.
Thanks #Sufian
http://json.parser.online.fr/
This does solve my problem
You should change your json. Your json data's id parameters doesn't have " character;
Control your id paramerters.
{"DistributorDealerList":
{[{"Id":"2",
"Name":"Distributor1",
"Dealer":
[{"Id":"1",
"Name":"Dealer1"},
{"Id":"2","
Name":"Dealer2"}]},
{"Id":"4","Name":"Distributor2",
"Dealer":
[{"Id":"3",
"Name":"Dealer3"}]}]}
The json provided by you is wrong.
I have solved you error in your json string
You can get this right json string from : http://pastie.org/private/1xbyzgamzihswnpgtz15yw
You can verify this json string using this url :
http://jsonviewer.stack.hu/
I hope it was helpfull.

Json Without Key to Parse in Android

I have this below Json which I'm getting from a .Net Web service:
[["Developer","test","developer#test.com"]]
I checked with jsonlint validator and It shows above json fine.
Because it is not having any key I don't know how to parse it in Android.
Can someone please help me how to parse this json without key.
If it had keys, I would have tried this:
{"first":"somevalue","last":"someothervalue"} // Json response
JSONObject json_obj = new JSONObject(resp); //response is the json array
String first = json_obj.getString("first");
String last = json_obj.getString("last");
String test = "Hello! " + first + " " + last;
Hope someone helps :)
Regards,
Praveen
MY SOLUTION
JSONArray respo = new JSONArray(resp); //resp is Json Array
respo = respo.getJSONArray(0);
String test = respo.getString(2);
test = "Your Email Address is " + test;
in Android (Java) parsing this line looks like:
String jsonString="[[\"Developer\",\"test\",\"developer#test.com\"]]";
try {
JSONArray jsonArray=new JSONArray(jsonString);
JSONArray jsonArray2=jsonArray.getJSONArray(0);
for (int i = 0; i < jsonArray2.length(); i++) {
String valueString=jsonArray2.getString(i);
Log.e("json", i+"="+valueString);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Use JSONArray instead of JSONObject. Then use the getJSONArray() function to get the array inside the array. After that you can access all values with their index and getString().

Parse JSON String array for individual strings/ints

I am getting information from a MySql DB via PHP. The information is returned in the following JSON array:
06-15 15:20:17.400: E/JSON(9865): {"tag":"get_game_state","success":1,"error":0,"GameState":{"monster":"Troll","qty":"1","exp":"0"}}
The json is parsed and string is built using StringBuilder. Now that I have the information returned I want to parse it for the individual strings/ints it contains to put them in a local sqlite db.
Here are the two lines in question
userFunctions.getServerGameState(email, monster, qty, exp); //this line gets the JSON array and the above information is returned
db.saveLocalGameSate(monster, qty, exp); //this line should take that information take String monster int exp and int qty and put them in the local db.
How should I convert that returned information into an individual string and ints so that they can be used in the next line of code? Any direction to some resources would be very helpful.
update
I have added the following lines inbetween the two above lines of code, output is a null pointer exception
try {
JSONArray arr = new JSONArray(GameState);
JSONObject jObj = arr.getJSONObject(0);
String virtumon = jObj.getString("monster");
Integer qty = jObj.getInt("qty");
Integer exp = jObj.getInt("exp");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
That's not actually a JSON array; it's a JSON object (cause of the curly braces instead of square brackets.)
One of the constructors to JSONObject() accepts a string containing JSON and will parse it and create a JSON object. I can't post links yet but see the JSONObject docs at d.android.com.
Once you have a JSONObject you can use getString(), getInt(), optString() and optInt() to pull out the data you need.
Assuming 'responseString' is the full response string:
try {
JSONObject responseObj = new JSONObject(responseString);
JSONObject gameStateObj = responseObj.getJSONObject("GameState");
String monsterType = gameStateObj.getString("monster");
int qty = Integer.parseInt(gameStateObj.getString("qty"));
int exp = Integer.parseInt(gameStateObj.getString("exp");
} catch (JSONException ex) {
e.printStackTrace();
}
"qty" and "exp" are strings in your json so you need to getString then convert to int. I think this code is correct; haven't tested it.

Categories

Resources