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.
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'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();
}
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
Basically I am trying to insert the JSON objects the app received into the SQLite database. As I named my JSON object in a continuous ID, I want to create a do while loop to count how many objects it received and stop when the maximum object is received.
My codes is following:
mydb.StoreMemberInfo(Integer.valueOf(json.getString(TAG_MEMBER_ID).toString()), json.getString(TAG_MEMBER_NAME), Integer.valueOf(json.getString(TAG_MEMBER_POINT).toString()));
do {
mydb.StoreShopInfo(Integer.valueOf(json.getString(TAG_SHOP_ID + ++shop_ID_counter).toString()), json.getString(TAG_SHOP_NAME + ++shop_name_counter));
}
while(TAG_SHOP_ID + shop_ID_counter != null);
The JSON objects my app is supposed to receive is as following:
{"success":1,"message":"Login successful","member_id":"1","member_name":"Peter","member_point":"1000","shop_ID_1":"1","shop_name_1":"Chatime","shop_ID_2":"2","shop_name_2":"Beard Papa","shop_ID_3":"3","shop_name_3":"CoolBlog","friend_ID_1":"2","friend_name_1":"James","friend_ID_2":"3","friend_name_2":"Mary"}
The loop is supposed to stop once it reached shop_ID_4 but because it does not exist but the code is in a waiting state and does not process the other codes instead. What should I do?
Can be worked on to do what you need I believe. Just copy and pasted from something I did a few months ago.
public List<LocationData> parseLocatonData(String response)
{
String result = response;
mLocationData = new ArrayList<LocationData>();
try {
JSONObject jsonObject = new JSONObject(result);
Boolean status = jsonObject.getBoolean("status");
if (status) {
JSONObject jObject = new JSONObject();
jObject = jsonObject.getJSONObject("results");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
LocationData locationData = new LocationData();
String key = keys.next();
JSONObject innerJObject = jObject.getJSONObject(key);
locationData.setLocationName(innerJObject.getString("cName"));
locationData.setCity(innerJObject.getString("cCity"));
locationData.setAddress(innerJObject.getString("cAddress"));
locationData.setFieldName(innerJObject.getString("cField"));
locationData.setState(innerJObject.getString("cState"));
locationData.setFieldUrl(innerJObject.getString("cWebsite"));
locationData.setZip(innerJObject.getString("cZip"));
mLocationData.add(locationData);
}
return mLocationData;
}
} catch (JSONException e) {
Toast.makeText(mContext, "Error getting Location Info", Toast.LENGTH_SHORT).show();
LogUtils.LOGI(TAG, e.toString());
}
return null;
}
The main thing is the key iterator, lets you walk down the list
I want to parse JSON with any key on Android.
JSON data consists of any key, array or values.
Here are JSON data and my working code.
I want to put JSON data into a class by using JSON parsing.
JSON data :
{
"d520c8c17c8e":
{ "id":"25689123",
"number":"0e31b1994"
},
"d183c6e9913d":
{
"id":"25689123",
"number":"0e31b1994"
},
"content":"8090986565488990",
"text":"hello",
"status":"ok"
}
My code :
public static MyInfo getMyInfo(JSONObject json) {
MyInfo info = new MyInfo();
if (json == null)
return null;
try {
info.setContent(json.getString("content"));
info.setText(json.getString("text"));
info.setStatus(json.getString("status"));
ArrayList<MyList> mylists = new ArrayList<MyList>();
JSONArray panels = json.getJSONArray(????????????);
for(int i=0;i < panels.length();i++){
JSONObject e2 = panels.getJSONObject(i);
MyList info_list = new MyList();
info_list.setId(e2.getString("id"));
info_list.setNumber(e2.getString("number"));
info_list.add(info_answer);
}
info.setList(info_list);
} catch (JSONException e) {
}
return info;
}
please help me.
Yes this is possible.
Put the JSON you receive in a JSONObject. You can loop trough the keys and get the values out of it.
Example:
//Create json object from string
JSONObject newJson = new JSONObject(json);
// Get keys from json
Iterator<String> panelKeys = newJson.keys();
while(panelKeys.hasNext()) {
JSONObject panel = newJson.getJSONObject(panelKeys.next()); // get key from list
String id = panel.getString("id");
String number = panel.getString("number");
}
I hope this is what you were looking for