{
"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
Related
I need to show response on Sign Up, below is my JSON Response.
I should show password is too short(minimum is 5 characters) into one string
{ errors: { password: [ "is too short (minimum is 5 characters)" ] } }
And also I need to parse the response from the following JSON data
as Signature has already been taken
{ errors: { signature: [ "has already been taken" ] } }
Please tell me how to parse the particular data from the JSON data.
Thanks in advance!!!!
You can use below method to parse your data.
private String parseJsonData(String jsonResponse) {
try {
JSONObject jsonObject = new JSONObject(jsonResponse);
JSONObject errorJsonObject = jsonObject.getJSONObject("errors");
JSONArray jsonArray = null;
//has method
if (errorJsonObject.has("password")) {
jsonArray = errorJsonObject.optJSONArray("password");
} else if (errorJsonObject.has(" signature")) {
jsonArray = errorJsonObject.optJSONArray("signature");
}
String errorMessage = jsonArray.getString(0);
return errorMessage;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
You can replace unwanted symbols like below code:
errorMessage.repalce("[","");
errorMessage.repalce("]","");
errorMessage.repalce("/"","");
You can use Google's Gson library to do that using the following steps:
Add dependency in your build.gradle(Module:app) file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
For latest version of gson library, click here
To parse JSON string to an object use the code below:
Gson gson = new Gson();
// I'm fetching my session stored JSON string
// You can fetch as per your requirement
String jsonStr = session.getJsonStr();
MyObject myObject = (MyObject) gson.fromJson(jsonStr, MyObject.class);
And if you need to convert an object to a JSON string, you can use the below code:
// I'm fetching my session stored Object here
// You can fetch as per your requirement
MyObject myObject = session.getMyObject();
String jsonStr = gson.toJson(myObject);
Make sure you design your object appropriate for the JSON string to match the data types. If you are not sure of the data types in the JSON, you can use this site or any parse and view website to view them.
Hope it helps!
Just try this,
try {
String tost = null;
JSONObject object = new JSONObject(json);
JSONObject errorObject = object.getJSONObject("errors");
if (errorObject.has("password")){
tost = "password "+errorObject.getJSONArray("password").get(0).toString();
} else if (errorObject.has("signature")){
tost = "signature "+errorObject.getJSONArray("signature").get(0).toString();
}
Toast.makeText(MainActivity.this, tost, Toast.LENGTH_SHORT).show();
}catch (Exception e){
e.printStackTrace();
}
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 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 need to get the value of idinside studentarray. The response I get is,
{
"response": {
"student": [
{
"id": "125745",
"module": 3,
"status": 1
}
]
}
}
I tried using following code,
String userId = null;
try {
JSONObject object = (JSONObject) new JSONTokener(response).nextValue();
userId= object.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
But it doesn't work. How do I retrieve id?
You are almost there, just you need to do this:
JSONArray students = object.getJSONArray("student");
JSONObject student = students.getJSONObject(0);
userId= student.getString("id");
Because the id value is placed in a JSONObject, then inside a JSONArray at index 0, then it is again placed inside a JSONObject.
Also don't forget to handle exceptions, the code above, is just for your understanding.
Hope that helps!!
Your value is placed in json array. So, you need to retrieve response object using getJSONObject and then get student json array via getJSONArray. Then you will be able to iterate through student objects. There is no way to magically get id from json.
Alternatively, you can map your json to Java objects using Gson, for example.
Try this :
Let all of the json is called
String serverResponse = "Response from the server";
try {
JSONObject object = new JSONObject(serverResponse);
String userId = object.getJSONObject("response").getJSONArray("student").getJSONObject(0).getString("id");
}
catch (JSONException e) {
e.printStackTrace();
}
Hope this helps.
Assuming jsonObject is a reference to your root json, you can get id of the first student:
JSONObject response = (JSONObject) jsonObject.get("response");
JSONArray students = (JSONArray) response.get("student");
int id = (int) ((JSONObject)students.get(0)).get("id");
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