I am using following piece of code for parsing JSON in my android application.
String result = postHttpResponse(uri, json);
try {
JSONObject jsonResult = new JSONObject(result);
boolean authenticated = jsonResult.getBoolean("Authenticated");
if(authenticated){
user = new User();
JSONObject jsonUser = (JSONObject) jsonResult.get("User");
user.setName(jsonUser.getString("Name"));
user.setUserId(jsonUser.getString("UserId"));
}
} catch (JSONException e) {
Log.e(TAG, e.getMessage());
}
jsonUser.getString("UserId") returns the value "corp\\ns0017" instead of "corp\ns0017". Actualy it is escaping the character "\" in the string with one more "\". but at the time of parsing i want to remove the extra "\". How can i achieve it?
Related
I am trying to parse this json.
However, it is not working ...
I want to parse expected_departure_time of all the buses such as 4 , 15, C1, 4A in departure
this is my code which is not working.
try{
String str = response.getString("departures");
JSONArray jsonArray = response.getJSONArray(str);
JSONObject bus = jsonArray.getJSONObject(0);
String four = bus.getString("expected_departure_time");
textView.append(four);
}catch (JSONException e){
e.printStackTrace();
}
JSON
https://transportapi.com/v3/uk/bus/stop/6090282/live.json?app_id=d7180b02&app_key=47b460aac35e55efa666a99f713cff28&group=route&nextbuses=yes
The error you're making is that you're considering "departures" as a JsonArray, which is not the case in your JSON example, it is a JsonObject (Which in my opinion is a poor way of constructing this Json).
Anyway, you will have to get all the JsonObjects inside the "departure" JsonObject by doing this:
try
{
String jsonString=response.toString();
JSONObject jObject= new JSONObject(jsonString).getJSONObject("departures");
Iterator<String> keys = jObject.keys();
while( keys.hasNext() )
{
String key = keys.next();
JSONArray innerJArray = jObject.getJSONArray(key);
//This is your example, you can add a loop here
innerJArray(0).getString("expected_departure_time");
}
}
catch (JSONException e)
{ e.printStackTrace(); }
If you need to use the transport API for other features, to convert JSON strings to Java objects, you can map automatically by using GSON.
Follow the instructions from Leveraging the gson library and map any response you want from this API.
I am developing the android app and i want to get the token from header using volley which is in server json response and store it in sq-lite for maintaining the session of user,i search everywhere bt i am not getting how to retrieve the token from json,please help me about this issue
this is my json response
{ "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI5ODkzMjY3OTQ0IiwiYXVkIjoid2ViIiwiZXhwIjoxNTA1ODEwNTQ5LCJpYXQiOjE1MDUyMDU3NDl9.cf9QGwp7zLVSTuiunClkauTFEXe6jtcNCxzqIntEtmWTDfLqAD3nKiXIf-fg0vEV_74SOcPVYxDcTUwCZqntVA" }
try this
JSONObject jsonObject = new JSONObject("your json string");
String token= jsonObject.optString("token");
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
String access_token= jsonObject.optString("access_token");
Log.v("####","hellow token " + access_token);
} catch (JSONException e) {
e.printStackTrace();
}
Try this
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
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.
{
"status": "ERROR",
"msg_content": "Your old password was entered incorrectly. Please enter it again.",
"code": "400",
"msg_title": "Sorry. Error in processing your request"
}
if (str.startsWith("Bad Request"))
{
textview.setText(" ");
}
How to print inside the textview to display the msg_content using json
You need to parse json using JSON object.
JSONObject obj = new JSONObject(str);
Then find string from JSON object whatever you want.
if (obj.has("msg_content")) {
String value = obj.getString("msg_content");
textview.settext(value);
}
You will need to create a JSONObject and pass it the string as a parameter.
JSONObject obj = new JSONObject(str);
Then to find a key in the JSONObject just call, always check if the JSONObject has that key before trying to retrieve it.
if (obj.has("status"){
String status = obj.getString("status");
}
if (obj.has("msg_content"){
String content = obj.getString("msg_content");
textview.setText(content);
}
JsonReader is implemented in API 11. If you want to use it in GingerBread or below try this
Use following Code for extracting Information from JSON Objects:
try {
Iterator keys = jsonObject.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
if(key.equals("msg_content"))
textView.setText(jsonObject.getString(key));
}
} catch (JSONException e) {
e.printStackTrace();
}
Also, if u have JSON as String, u can populate an object using following code:
try {
jsonObject = new JSONObject(theJsonString);
} catch (JSONException e1) {
e1.printStackTrace();
}
I'm quite new to JSON but I would create a JsonReader and parse the JSON as per here