I have a response String from an API service like this :
{"id":"login","status":"true"}
and This is the way to parse Response String to get Value from Key "Status"
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
}
catch(JSONException e){
e.printStackTrace();
}
JSONArray innerJsonArray = null;
try {
innerJsonArray = jsonObj.getJSONArray("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObject = null;
try {
jsonObject = innerJsonArray.getJSONObject(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println(jsonObject.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and I've got error
"org.json.JSONArray cannot be converted to JSONObject"
Anyone can give me suggestion?
JSONObject jsonObj = null;
try{
jsonObj = new JSONObject(responseString);
System.out.println(jsonObj.getString("status"));
}
catch(JSONException e){
e.printStackTrace();
}
You do not need to bother with any other arrays.
In which line you get the exception ? In any way may be you should use
jsonObj =JSONObject.fromObject(responseString);
Kindly try the snippet code below. Try this link for gaining better knowledge about parsing an JSON response.
JSONObject jObj;
try {
jObj = new JSONObject(responseString);
Log.i("id==", jObj.getString("id"));
Log.i("status==", jObj.getString("status"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
How can I convert String to HttpInputMessage?
or HttpResponse to HttpInputMessage
Post (return json):
HttpResponse<String> jsonResponse = null;
try {
jsonResponse = Unirest.post(targetURL).header("Accept", "application/json")
.header("Content-Type", "application/json;").body(urlParameters).asString();
} catch (UnirestException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String str = jsonResponse.toString();
HttpInputMessage inputMessage = null;
return inputMessage;
I want convert json to Object
RoutesList routes = new RoutesList();
Post post = new Post(this.url + allRoutes, depoId.toString());
HttpInputMessage inputMessage = null;
try {
inputMessage = post.getResult();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
converter.read(routes.getClass(), RoutesList.class, inputMessage);
} catch (HttpMessageNotReadableException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can wrap the HttpResponse using this class HttpComponentsAsyncClientHttpResponse:
HttpComponentsAsyncClientHttpResponse(HttpResponse httpResponse)
And return it as HttpInputMessag, for example:
return new HttpComponentsAsyncClientHttpResponse(jsonResponse)
this class implement the interface HttpInputMessage.
response
deneme2="{\"NUKE_USER_NO\":\"1494\",\"WEB_PIN\":\"metin\",\"CARI_NO\":\"2611\",\"FIRMA_ADI\":\"\",\"CARI_UNVANI\":\"LTDSTI\",\"MOD\":\"Müşteri\",\"RENK\":\"'#fbbb5e'\",\"EMAIL\":\"yok\",\"SAHIS_NO\":\"9\",\"ADISOYADI\":\"Metin\",\"YETKILER\":\"UrunListesi, KampanyaList, YeniUrunler, SepetListe, SiparisTakip, BekleyenSiparisler, TaksitBilgi, TaksitliOdeme, CariEkstre, HavaleEftBildir, BankaHesapNumaralari, PcShirbazi, IadeTalep, IadeSonuclari, GarantiSorgulama, ArizaTakip, UyelikBilgilerim, KullaniciList, SevkAdres, CariHareketler, BorcAlacakDurumu, AlisAnalizi, AlisCirolari, BABS, StandartFormlar, ArizaIadeProseduru, SevkiyatProseduru, Organizasyon, Iletisim, SiparisVerme, GuvenliOdeme3D, MailOrderOranlari, KargoTakip, FiyatMod, AnaSayfa, MusteriTemsilcisiniGorsun, Ihaleler, Puanlarim, UyeIsyeri, IadeDegerlendir, IadeSonucDepo\",\"CARI_TIP_NO\":\"6\",\"AKTIF_SEPET\":\"197\",\"KAR_MARJI\":\"0\",\"ODEME_NO\":\"21\",\"DOVIZ_BIRIMI\":\"USD\",\"NAKLIYE_TIP_NO\":\"11\",\"ROLE_ADI\":\"Bayi\"}";
Java code
public JSONObject stringToJson(String deneme2)
{
JSONObject json= new JSONObject();
try {
json.getString(deneme2);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
and then error and exception. It doesn't change string value JSONObject
http://i.stack.imgur.com/roVu5.png
Firstly:
JSONObject json= new JSONObject();
is not taking the actual String which need to be converted.
public JSONObject stringToJson(String deneme2)
{
JSONObject json= new JSONObject(deneme2); //pass a String here
try {
json.getString("key name"); //key for which you need to retrieve data
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
Hope it helps.
deneme2 is string value and deneme2 is JSON writing format. and then i sent deneme2 stringToJson function for string to JSON object bu return exceptation in image and null json.
Try this it will help you : Firstly convert above String to json object
JSONObject jsonobject = new JSONObject(deneme2);
try {
String abc = json.getString("NUKE_USER_NO");
Log.i("Log", abc);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 8 years ago.
I am encounter a problem. I have following xml
<string>[{"BatchIDs":[],"HomeWorkCategoryName":"","FileURL":"","FileName":"","ID":1,"Title":"test","Description":"test","HomeworkCategoryID":1,"ExpiryDate":"\/Date(1386658800000)\/","FileID":-2147483648,"URL":"","Mode":1,"Type":2,"Status":1,"CreatedOnDate":"\/Date(1388093500883)\/","UpdatedOnDate":"\/Date(1388093500883)\/","Inactive":false,"Deleted":true},
{"BatchIDs":[],"HomeWorkCategoryName":"","FileURL":"","FileName":"","ID":1,"Title":"test","Description":"test","HomeworkCategoryID":1,"ExpiryDate":"\/Date(1386658800000)\/","FileID":-2147483648,"URL":"","Mode":1,"Type":2,"Status":1,"CreatedOnDate":"\/Date(1388093500883)\/","UpdatedOnDate":"\/Date(1388093500883)\/","Inactive":false,"Deleted":true},
{"BatchIDs":[],"HomeWorkCategoryName":"","FileURL":"","FileName":"","ID":1,"Title":"test","Description":"test","HomeworkCategoryID":1,"ExpiryDate":"\/Date(1386658800000)\/","FileID":-2147483648,"URL":"","Mode":1,"Type":2,"Status":1,"CreatedOnDate":"\/Date(1388093500883)\/","UpdatedOnDate":"\/Date(1388093500883)\/","Inactive":false,"Deleted":true}]
And I want to read all values passed in this xml. This xml is single string return by web service. Currently I am using following code (it's also providing null value for first entry)
Object result = envelope.getResponse();
str=result+"";
String key,value;
String[] couple = str.split(",\"");
for(int i =0; i < couple.length ; i++) {
String[] items =couple[i].split(":");
key=items[0];
value=items[1];
key=key.replaceAll("\"", "");
value=value.replaceAll("\"", "");
/* some conditions to fetch values */
}
Please tell me how can I get exact values and keys in android.
Thanks,
It seems to be a valid json. You can use http://jsonlint.com/ to check that.
So with this following class : JSONArray, you can retrieve what you want.
Thanks everyone for helping me.
Here is my soluction through I overcome my problem. May be it will use for others
HttpGet httpRequest = new HttpGet(_URL);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpresponse = httpclient.execute(httpRequest);
JSONArray response = null;
try {
response = new JSONArray(getJSONString(httpresponse));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (int i = 0; i < response.length(); i++) {
try {
//your values
String _name=response.getJSONObject(i).getString("NAME");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Here is 2nd function.If your function is parse through xml code.
public static String getJSONString(HttpResponse response) {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(response.getEntity().getContent());
NodeList nl = doc.getElementsByTagName("string");
Node n = nl.item(0);
String str = n.getFirstChild().getNodeValue();
return str;
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
Happy Coding
I am reading some JSON from with in an Android App, yet it will not recognise the following JSON
{"value":"1000","make":"Ford","model":"Focus","desc":"1.9 Zetec","Fuel":"petrol"}
This is output generated from a PHP file on a webserver. Is there something wrong with this JSON or is the problem with the following code?
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String car_value = json_data.getString("value");
Log.e("JSON",car_value);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Given String is not a Json Array. That is Json Object. So parse with Json object.
like below
try {
JSONObject jObject = new JSONObject(result);
String value = jObject.getString("value");
String make = jObject.getString("make");
// TODO and so on
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The json data you are receiving is not a JSONArray. It is a JSONObject. So, you should receive it as:
JSONObject jArray = new JSONObject(result);
And then if you want value you can get it like
String car_value = jArray.getString("value");
I have a JsonObject based Class called JSONParse. There is this method:
public String getName()
{
try {
JSONObject jobj = this.getJSONObject("Data");
Log.e("NFF NAME", jobj.toString());
JSONObject jobj2= jobj.getJSONObject("User");
Log.e("NFF NAME", jobj2.toString());
return jobj2.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
The Log:
03-19 19:50:09.280: E/NFF NAME(5909): {"User":{"picture":"http://vm19.htl-leonding.ac.at/img/30.png","gender":"f","username":"lisa","age":32}}
03-19 19:50:09.280: E/NFF NAME(5909): {"picture":"http://vm19.htl-leonding.ac.at/img/30.png","gender":"f","username":"lisa","age":32}
Problem:
This method above always returns null for the name.
Please Help
username is inside User... try this
public String getName()
{
try {
JSONObject jobj = this.getJSONObject("Data");
Log.e("NFF NAME", jobj.toString());
JSONObject jobj2= jobj.getJSONObject("User");
Log.e("NFF NAME", jobj2.toString());
JSONObject jobj2b= jobj2.getJSONObject("User");
Log.e("NFF NAME", jobj2b.toString());
return jobj2b.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
i don't tested but you may try...
EDITED:
i'm sorry, i write fast and dont look at the code, jobj2b point to jobj2 first child: 'User'