String jsonStr = HelperInputStream.convertInputStreamToString(inputStream);
if (jsonStr == null) {
return;
}
String code,message = "";
try {
JSONObject object = new JSONObject(jsonStr);
Log.e("code:" , object.getString("subject"));
jsonStr result is:
[{"code":"1","subject":"you have new message"}]
unfortunately i get this error is catch:
org.json.JSONException: Value [{"subject":"you have new message","code":"1"}] of type org.json.JSONArray cannot be converted to JSONObject
whats my code problem. in server i have only this code:
<?php
echo json_encode(array(
array(
'code'=>'1',
'subject'=>"you have new message",
)
));
?>
subject key is in JSONObject which is inside JSONArray so get JSONArray from jsonStr string:
JSONArray arrJSON = new JSONArray(jsonStr);
JSONObject object=arrJSON.getJSONObject(0);
Log.e("code:" , object.getString("subject"));
Related
my code already get data(jsonstr) from website but can't make it to JSONObject and it make error Json parsing error: Unterminated object at character 2755
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("Destinasi");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String nim = c.getString("nama_destinasi");
String name = c.getString("alamat_destinasi");
String alamat= c.getString("deskripsi_destinasi");
and this link that i try to parse
https://ombajuom.000webhostapp.com/json_destinasi.php/Destinasi
please help me and sorry for my english
I see a misplaced ] and } in JSON String. The String it returns NOW is as follows
{
"Destinasi": [
{
"nomor_id": "1",
"nama_destinasi": "Ravi Tamada",
"alamat_destinasi": "Ciledug",
"deskripsi_destinasi": "WAhhh",
"rating_destinasi": "3"
]
}
}
But it should be as below to make it a valid JSON.
{
"Destinasi": [
{
"nomor_id": "1",
"nama_destinasi": "Ravi Tamada",
"alamat_destinasi": "Ciledug",
"deskripsi_destinasi": "WAhhh",
"rating_destinasi": "3"
}
]
}
Web service you shared is not a valid JSON format, to validate your response you can use jsonlint.com,
Thanks
I have some JSON with the following structure:
{
"items":[
{
"product":{
"product_id":"some",
"price_id":"some",
"price":"some",
"title_fa":"some",
"title_en":"Huawei Ascend Y300",
"img":"some",
"has_discount_from_price":"0",
"discount_from_price":null,
"type_discount_from_price":null,
"has_discount_from_product":"0",
"discount_from_product":null,
"type_discount_from_product":null,
"has_discount_from_category":"0",
"discount_from_category":null,
"type_discount_from_category":null,
"has_discount_from_brand":"0",
"discount_from_brand":null,
"type_discount_from_brand":null,
"weight":null,
"features":[
{
"feature_value":"#000000",
"feature_id":"some",
"feature_title":"some"
},
{
"feature_value":"some",
"feature_id":"1652",
"feature_title":"some"
}
]
},
"number":1,
"feature_id":"56491,56493",
"price_inf":{
"has_discount":0,
"discount_type":0,
"final_price":"400000",
"value_discount":0
},
"cart_id":13
}
]
}
I'm trying to access the elements "product_id" and "price_id" with the following Java code:
try{
JSONArray feedArray=response.getJSONArray("items");
for (int i=0;i<feedArray.length();i++){
JSONObject feedObj=feedArray.getJSONObject(i);
JSONObject pro=feedObj.getJSONObject("product");
Product product = new Product();
product.setPrice(pro.getDouble("price_id"));
product.setTitle_fa(pro.getString("price_id"));}}
but i see product not found error.what is wrong in my parser?
First of all your JSON is valid. So no worries there.
Now regarding your problem, because you haven't posted the logs so I can't tell what the exact problem is. But using this code snippet you can get the desired values.
try {
JSONArray itemsJsonArray = jsonObject.getJSONArray("items");
for (int i = 0; i < itemsJsonArray.length(); i++){
JSONObject itemJsonObject = itemsJsonArray.getJSONObject(i);
JSONObject productObject = itemJsonObject.getJSONObject("product");
String productId = productObject.getString("product_id");
String priceId = productObject.getString("price_id");
}
} catch (JSONException e) {
e.printStackTrace();
}
Validate and create Pojo for your json here
use
Data data = gson.fromJson(this.json, Data.class);
follow https://stackoverflow.com/a/5314988/5202007
By the way your JSON is invalid .
you are getting a json object from your response not json array you need to make following changes
JSONObject temp =new JSONObject(response);
JSONArray feedArray=temp.getJSONArray("items");
Try converting response string to JSONObject first
try{
JSONObject temp =new JSONObject(responseString); // response is a string
JSONArray feedArray=.getJSONArray("items");
....
}
You may try to use GSON library for parsing a JSON string. Here's an example how to use GSON,
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
I parse the JSON String and face the error
org.json.JSONException: Unterminated object at character 25
my JSON is retrieved from Facebook
{Response: responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[{"venue":{"id":108242939200809,"zip":"","longitude":11.4,"latitude":62.5833,"street":""},"location":"Røros, Norway","eid":1473462312875161,"pic_big":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yn\/r\/5uwzdFmIMKQ.png","pic_small":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yy\/r\/XcB-JGXohjk.png","description":"Test","name":"Test"},{"venue":{"id":105818232792451,"zip":"","longitude":108.217,"latitude":16.0167,"street":""},"location":"Hòa Vang","eid":1425682134338854,"pic_big":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yn\/r\/5uwzdFmIMKQ.png","pic_small":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yy\/r\/XcB-JGXohjk.png","description":"test","name":"Test"}]}}, error: null, isFromCache:false}
My JSON parser is
public static JSONArray parse(Response response) throws JSONException{
JSONArray jsonArray=new JSONArray(response.toString());
return jsonArray;
}
Please help me. Thank you very much.
This is, May be because you are trying to parse response after coverting your response into String with response.toString()
So if your response is
{"title":"This is Title","message":"This is message"}
and you converted it to String with response.toString()
Then your response will be like this
{title:This is Title,message:This is message}
So you are trying to parse response of type String and the compiler will not be able to parse that response and it will throws an error like Unterminated object at character......
So make sure that you are parsing valid JSON.
EDIT ( Credit : Dhruv Raval for below edited solution )
You may solve this by:
Before:
GraphResponse response;
JSONObject jObjResponse = new JSONObject(response.toString());
After:
GraphResponse response;
JSONObject jObjResponse = new JSONObject(String.valueOf(response.getJSONObject()));
i m getting same error & solving them like:
GraphResponse response;
Before:
JSONObject jObjResponse = new JSONObject(response.toString());
After:
JSONObject jObjResponse = new JSONObject(String.valueOf(response.getJSONObject()));
Just use JSONObject graphObj =response.getJSONObject(); and you will get the graphObject.
Your JSON is invalid. All variable names need to be quoted.
Change
JSONArray jsonArray=new JSONArray(response.toString());
to
JSONObject start = new JSONObject(String.valueOf(response.getJSONObject()));
then direct call
JSONArray data = start.getJSONArray("data");
It gives you the "Data" JSON Array.
try {
JSONObject jsonData = response.getJSONObject();
JSONArray jsonArray = jsonData.getJSONArray("data");
Log.e("MainActivity ", "jsondata --> " + jsonArray.toString(2));
Log.e("MainActivity ", "jsonArray.length()-> " + jsonArray.length());
likesPojos.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
Log.e("MainActivity ", "message --> " + json.getString("name"));
Log.e("MainActivity ", "id --> " + json.getString("id"));
LikesPojo likesPojo = new LikesPojo();
likesPojo.setId(json.getString("id"));
likesPojo.setName(json.getString("name"));
likesPojos.add(likesPojo);
}
} catch (Exception e) {
e.printStackTrace();
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Determine whether JSON is a JSONObject or JSONArray
I have a server that returns some JSONArray by default, but when some error occurs it returns me JSONObject with error code. I'm trying to parse json and check for errors, I have piece of code that checks for error:
public static boolean checkForError(String jsonResponse) {
boolean status = false;
try {
JSONObject json = new JSONObject(jsonResponse);
if (json instanceof JSONObject) {
if(json.has("code")){
int code = json.optInt("code");
if(code==99){
status = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return status ;
}
but I get JSONException when jsonResponse is ok and it's a JSONArray (JSONArray cannot be converted to JSONOBject)How to check if jsonResponse will provide me with JSONArray or JSONObject ?
Use JSONTokener. The JSONTokener.nextValue() will give you an Object that can be dynamically cast to the appropriate type depending on the instance.
Object json = new JSONTokener(jsonResponse).nextValue();
if(json instanceof JSONObject){
JSONObject jsonObject = (JSONObject)json;
//further actions on jsonObjects
//...
}else if (json instanceof JSONArray){
JSONArray jsonArray = (JSONArray)json;
//further actions on jsonArray
//...
}
You are trying the convert String response you get from Server into JSONObject which is causing the Exception. As you said you will get the JSONArray from Server, you try to convert into JSONArray. Please refer this link which will help you when to convert string response to JSONObject and JSONArray. If you response starts with [ (Open Square Bracket) then convert it to JsonArray as below
JSONArray ja = new JSONArray(jsonResponse);
if your response starts with { (open flower Bracket) then convert it to
JSONObject jo = new JSONObject(jsonResponse);
I am using this code for detect the source language..
jsonObj = new JSONObject(response);
JSONObject jsoObj2 = jsonObj.getJSONObject("data");
JSONArray jArray = jsoObj2.getJSONArray("detections");
JSONObject steps = jArray.getJSONObject(0);
srcLanguage = steps.getString("language");
Here is the response.
{
"data": {
"detections": [
[
{
"language": "fr",
"isReliable": false,
"confidence": 0.41935483
}
]
]
}
}
Kindly help me in order to parse this json response.
I debug that code and getting this exception.
org.json.JSONException: Value [{"isReliable":false,"confidence":0.41935483,"language":"fr"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject
Change it to this:
jsonObj = new JSONObject(response);
JSONObject jsoObj2 = jsonObj.getJSONObject("data");
JSONArray jArray = jsoObj2.getJSONArray("detections");
JSONArray jArray2 = jArray.getJSONArray(0);
JSONObject steps = jArray2.getJSONObject(0);
srcLanguage = steps.getString("language");
Because there is an array in the array.
If above mentioned is the response you need to have a minor change
jsonObj = new JSONObject(response);
JSONObject jsoObj2 = jsonObj.getJSONObject("data");
JSONArray jArray = jsoObj2.getJSONArray("detections");
JSONArray steps = jArray.getJSONArray(0);
srcLanguage = jArray.getJSONObject(0).getString("language");
Try his please...