I'm working on parsing some JSON in my android application, this is the code I started off with:
JSONObject jsonObject = **new JSONObject(result);**
int receivedCount = **jsonObject.getInt("CurrentCount");**
However this is causing it to error (The code that would error is surrounded with asterisks) in Android Studio, I tried using the suggestion feature which asked me if I want "Surround with try/catch" which would cause the app to crash when it launched.
This is the suggested code:
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
} catch (JSONException e) {
e.printStackTrace();
}
int receivedCount = 0;
try {
receivedCount = jsonObject.getInt("CurrentCount");
} catch (JSONException e) {
e.printStackTrace();
}
This is the JSON I'm trying to pass:
[{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
Thanks in advance!
J_Dadh I think first of all you should look through the documentation on how to use Json Parser which you can find in the following Link https://www.tutorialspoint.com/android/android_json_parser.htm
EXAMPLE JSON
{
"sys":
{
"country":"GB",
"sunrise":1381107633,
"sunset":1381149604
},
"weather":[
{
"id":711,
"main":"Smoke",
"description":"smoke",
"icon":"50n"
}
],
"main":
{
"temp":304.15,
"pressure":1009,
}
}
String YourJsonObject = "JsonString"
JSONObject jsonObj = new JSONObject(YourJsonObject);
JSONArray weather = jsonObj.getJSONArray("weather");
for (int i = 0; i < weather.length(); i++) {
JSONObject c = weather.getJSONObject(i);
String id = c.getString("id");
String main= c.getString("main");
String description= c.getString("description");
}
as you pasted your JSON you are using [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
-If we analyze this JSON,This JSON contains a JSON ARRAY [{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}]
having 3 JSON Objects{"CurrentCount":"5"},{"CurrentCount":"0"},{"CurrentCount":"1002"}
-But when you are going to parse this JSON, you are accepting it as jsonObject = new JSONObject(result),but you should accept it asJSONArray jsonArray=new JSONArray(result);
and then you iterate a loop(e.g,for loop) on this jsonArray,accepting JSONObjects 1 by 1,then getting the values from the each JSONObject 1 by 1.
-1 more mistake in your JSON is that you are sending the strings as "5" but accepting it as getInt() that's not fair,you should send int to accept it as intas 5 (without double qoutes)
So you final JSON and code like this(as below)
JSON
[{"CurrentCount":5},{"CurrentCount":0},{"CurrentCount":1002}]
Code to Use this JSON
JSONOArray jsonArray = null;
try{
jsonArray = new JSONArray(result);
for(int i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray[i];
receivedCount=jsonObject.getInt("CurrentCount");
}
}catch(JSONException e) {
e.printStackTrace();
}
Related
I have a bug in the code, but I can not find it. I have to read the message and the code from the JSON request below.
try {
Log.d("qwertz", json);
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("win"))
{
showDialog("Du hast etwas gewonnen", message,code);
}
else if (code.equals("false"))
{
showDialog("Du hast leider nichts gewonnen", message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
That is a JSON example
{
"server_response": {
"code": "win",
"message": "Du hast einen PzKpfw S35 739(f) gewonnen"
}
}
I advice you not to process json directly by yourself, instead you can use many libraries that will do the job for you. To mention you can use jackson or gson.
If you still want to correct your code you can try this:
JSONObject response = jsonObject.getJsonObject("server_response");
String code = response.getString("code");
I have a problem with JSON
I get a json since https://proxyepn-test.epnbn.net/wsapi/epn
But when I want to display a single data eg "name".
The console displays:
Log
org.json.JSONException: No value for Name
org.json.JSONException: Value status at 0 of the type java.lang.String can not be converted to JSONObject
Can you help me ?
Thanks.
here is my code :
String test2 = test.execute(restURL).get().toString();
Log.i("result",test2);
JSONObject obj = new JSONObject(test2);
String data = obj.getString("data");
Log.i("testjson",data);
String pageName = obj.getJSONObject("data").getString("Name");
Log.i("testjsondata",pageName);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
Try below:
JSONObject obj = new JSONObject(test2);
JSONObject data = obj.getJSONObject("data");
Iterator<String> iterator = data.keys();
while(iterator.hasNext()){
String key = iterator.next();
String Name = data.getString(key);
}
JSONObject obj = new JSONObject(test2);
JSONObject data=obj.getJSONobject("data");
JSONObject ob1=obj.getJSONobject("1");
String pageName = ob1.getString("Name");
You have to parse your next level of JSONObject (labeled as "1","2","3".. from response).
It seems like issue in Json response structure you shared. why cann't it be array inside "data"?
Then you can easily read data as JSONArray with those objects as ("1","2","3"..) array item.
Else
Android JSON parsing of multiple JSONObjects inside JSONObject
I have to send request body in Http request in below format:
{
"flag":false,
"Ids":["xyz","abc"]
}
I was trying like:
LinkedHashMap<String, Object> requestParamsMap = new LinkedHashMap<String, Object>();
requestParamsMap.put("flag",false);
ArrayList<String> IdList = new ArrayList<>();
IdList.add("xyz");
IdList.add("abc");
requestParamsMap.put("Ids", IdList.toString());
And then I was converting requestParamsMap to json string. But I am not getting request body in desired format.
I want to create a generalized method which can return me data in this type of format, so that I can use it throughout application.
Any help would be appreciated.. !!!
Do something like this:
JSONObject object=new JSONObject();
try {
object.put("flag","xyz");
JSONArray array=new JSONArray();
array.put("xyz");
array.put("abc");
object.put("Ids",array);
//added a log to see the output
Log.e("output",object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
object.toString() should contain exactly the json you want in string format. You can use a loop to populate the contents of the jsonArray or JSONObject depending on the number of items you have
Its not that though at all, output you want is JSONArray inside JSONObject and JSONObject inside another JSONObject. So, you can create them seperately and then can put in together. as below.
CODE
try {
JSONObject parent = new JSONObject();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
jsonArray.put("lv1");
jsonArray.put("lv2");
jsonObject.put("mk1", "mv1");
jsonObject.put("mk2", jsonArray);
parent.put("root", jsonObject);
Log.d("output", parent.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
OUTPUT
{
"root": {
"mk1": "mv1",
"mk2": [
"lv1",
"lv2"
]
}
}
Raw Json Data
[
{
"worker.1":{
"last_share":1443639029,
"score":"3722204.62578",
"alive":true,
"shares":1124332,
"hashrate":1047253
},
"worker.2":{
"last_share":1443639029,
"score":"3794755.69049",
"alive":true,
"shares":1069332,
"hashrate":1012070
},
"worker.3":{
"last_share":1440778690,
"score":"0.0",
"alive":false,
"shares":0,
"hashrate":0
},
"worker.4":{
"last_share":1443638222,
"score":"940190.67723",
"alive":true,
"shares":449932,
"hashrate":404772
}
"worker.nth":{
"last_share":1443638222,
"score":"940190.67723",
"alive":true,
"shares":449932,
"hashrate":404772
}
}
]
From the main question I have been able to narrow down the results and managed to add the Square bracket as well. Now i have a Json Array above so could someone advise me how can i process this Json array. Also note that it can end up being 1000 workers.
Please please help I have been breaking my head for 2 days on this,
Also note that the actual Json data is complex and 1000's of entries,
The json data included is just an overview.
Edit: Code that I ma using to process the above Json
try{
JSONArray jArray = new JSONArray(jsonObj.getJSONObject("workers"));
if(jArray.length() == 0){
Log.d("Json Err", "JSON string has no entries");
return null;
}
JSONObject jObject = jArray.getJSONObject(0);
// To get one specific element:
JSONObject worker1 = jObject.getJSONObject("worker.1");
JSONObject worker2 = jObject.getJSONObject("worker.2");
// Iterate over all elements
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next(); // "worker.1", etc
if ( jObject.get(key) instanceof JSONObject ) {
JSONObject entry = jObject.getJSONObject(key);
// Do something with your entry here like:
String score = entry.optString("score", "");
Boolean alive = entry.optBoolean("alive", false);
Integer shares = entry.optInt("shares", 0);
Log.d("Json Success", score );
}
}
} catch (JSONException e){
Log.e("Json Err", "Failure converting JSON String", e);
}
Error that I am getting:
E2570 (5:10 PM):
org.json.JSONException: Value {"worker.1":{"last_share":1443694390,"score":"15.6018529132","alive":true,"shares":59880,"hashrate":0},"worker.2":{"last_share":1443694180,"score":"2.97304689833","alive":true,"shares":2048,"hashrate":0},"worker.3":{"last_share":1440778690,"score":"0.0","alive":false,"shares":0,"hashrate":0},"ivonme.ant4":{"last_share":1443701343,"score":"8688.78118933","alive":true,"shares":203088,"hashrate":78633}}
of type org.json.JSONObject cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java)
at org.json.JSONArray.(JSONArray.java)
at org.json.JSONArray.(JSONArray.java)
So you have...
{ //JSONObject
"worker.1":{
"last_share":1443639029,
"score":"3722204.62578",
"alive":true,
"shares":1124332,
"hashrate":1047253
},
"worker.2":{
"last_share":1443639029,
"score":"3794755.69049",
"alive":true,
"shares":1069332,
"hashrate":1012070
} //,...
}
To get all your workers you have to...
try{
JSONObject jObject = new JSONObject(yourStringFromYourQuestion);
// To get one specific element:
JSONObject worker1 = jObject.getJSONObject("worker.1");
JSONObject worker2 = jObject.getJSONObject("worker.2");
// Iterate over all elements
Iterator<?> keys = jObject.keys();
while( keys.hasNext() ) {
String key = (String)keys.next(); // "worker.1", etc
if ( jObject.get(key) instanceof JSONObject ) {
JSONObject entry = jObject.getJSONObject(key);
// Do something with your entry here like:
String score = entry.optString("score", "");
Boolean alive = entry.optBoolean("alive", false);
Integer shares = entry.optInteger("shares", 0);
}
}
} catch (JSONException e){
Log.e(LOG_TAG, "Failure converting JSON String", e);
}
Try this:
JSONArray jArray=jsonObj.getJSONArray("workers");
instead of
JSONArray jArray = new JSONArray(jsonObj.getJSONObject("workers"));
The error is because of you are getting json array as object. I think so.
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