devs I am stuck in parsing this kind of JSON I don't understand how to get the value of status and message any help will be very appreciable. I get the value of error but when I want to access the value of status and message it throws an error
JSON Format :
{
"error": {
"status": 400,
"message": "Wrong number of segments"
}
}
My code for parsing json :
try {
JSONObject jso = new JSONObject(String.valueOf(response));
//jso.getJSONObject("error").getJSONObject("message");
jso.getJSONObject("error");
jso.getJSONObject("status").toString(200);
Log.d(TAG,"jso1"+jso);
} catch (JSONException e) {
e.printStackTrace();
}
JSONParser parser = new JSONParser();
JSONObject jso = (JSONObject) parser.parse(String.valueOf(response));
The above command will give you the response as JSON.
To get Status and message, you need to extract error as a separate JSONObject and then parse status and message
JSONObject errorObj = (JSONObject) jso.get("error");
String message = errorObj.get("message").toString();
int status = Integer.parseInt(errorObj.get("status").toString());
Remember to parse and retrieve using the hierarchy.. so if the status & message are inside "error", then extract error as a JSONObject and then retrieve the child keys. And as a good practice check if the key exists or not:-
if(errorObj.has("")) {
// do something
}
Adding a working sample :-
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
private static void parseJsonTest() {
String json = "{\n" +
" \"error\": {\n" +
" \"status\": 400,\n" +
" \"message\": \"Wrong number of segments\"\n" +
" }\n" +
"}";
try {
JSONParser parser = new JSONParser();
JSONObject jso = (JSONObject) parser.parse(json);
JSONObject errorObj = (JSONObject) jso.get("error");
String message = errorObj.get("message").toString();
int status = Integer.parseInt(errorObj.get("status").toString());
System.out.println(message + " >>>>>>> " + status);
} catch (Exception e) {
}
}
Output :-
Wrong number of segments >>>>>>> 400
try {
JSONObject jso = new JSONObject(String.valueOf(response));
//jso.getJSONObject("error").getString("message");
jso.getJSONObject("error");
jso.getJSONObject("error").getInt("status"); // if it was string use getString or it was int than use value getInt
Log.d(TAG,"jso1"+jso);
} catch (JSONException e) {
e.printStackTrace();
}
Try This
try {
JSONObject fullResponse = new SONObject(String.valueOf(response));
JSONObject errorData = fullResponse.getJSONObject("error");
String errorCode = errorData.getObject("status");
String errorMessage = errorData.getString("message");
Log.d(TAG,"Result = "+errorCode +" - "+errorMessage );
} catch (JSONException e) {
e.printStackTrace();
}
the Best way to convert Json to java it's to use converters libraries such as Gson
check the link below :
https://github.com/google/gson
Related
Good morning everyone I want to get the "transactionid: and it "value" from a json object but I am getting some error I need your helps.
Ex:
request= {"amount":"5.0","msisdn":"233200343913","transactionid":"0000001853860636"}
Here is my code
try{
JSONObject jsonObject = new JSONObject(request);
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext()){
String key = (String)keys.hasNext();
JSONArray value = jsonObject.getJSONArray(key);
}
}catch (Exception e){
e.printStackTrace();
}
But the string key = (String)keys.hasNext() given error I need your help, please.
If you want to get the value of specific field, you can do it like this
try{
JSONObject jsonObject = new JSONObject(request);
String value = (String) jsonObject.get("transactionid");
}catch (Exception e){
e.printStackTrace();
}
If you want to get all the fields and their values, you can do something like the following
try{
JSONObject jsonObject = new JSONObject(request);
Iterator<?> keys = jsonObject.keys();
while (keys.hasNext()){
String key = (String) keys.next();
String value = (String) jsonObject.get(key);
System.out.println(key + " - " + value);
}
}catch (Exception e){
e.printStackTrace();
}
I want to fetch only PersonNumber value from below JSON sample using java.
{"Context":[{"PersonNumber":"10","DMLOperation":"UPDATE","PeriodType":"E","PersonName":"Ponce","WorkerType":"EMP","PersonId":"1000","PrimaryPhoneNumber":"1","EffectiveStartDate":"2018-01-27","EffectiveDate":"2018-01-27"}],"Changed Attributes":[{"NamInformation1":{"new":"Ponce","old":"PONCE"}},{"FirstName":{"new":"Jorge","old":"JORGE"}},{"LastName":{"new":"Ponce","old":"PONCE"}}]}
Below is my code:
for (SyndContentImpl content : (List<SyndContentImpl>) entry.getContents()) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(content.getValue().toString());
System.out.println(jsonObj.get("Context"));
} catch (JSONException e) {
e.printStackTrace();
} }
You have to access to the path Context[0].PersonNumber.
This can be done with
String personNumber = jsonObj.getJSONArray("Context").getJSONObject(0).getString("PersonNumber");
I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:
{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10n"}],"base":"stations","main": ...more json
I have this method below which writes the string to a .json and allows me to get the values from it.
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.get("weather"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?
You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.
var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
" \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
var main = JsonPath.read(json, "$.weather[0].main"); // Rain
you can use
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array
or you can declare user defined class according to structure and convert code using GSON
Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());
From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject.
Try something like :
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject jobj = (JSONObject) obj;
JSONArray jobjWeatherArray = jobj.getJSONArray("weather")
for (int i = 0; i < jobjWeatherArray.length(); i++) {
JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
System.out.println(jobjWeather.get("id"));
System.out.println(jobjWeather.get("main"));
System.out.println(jobjWeather.get("description"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
I'm getting JSON parsing error while running my app
Below mentioned the code where I'm facing the error and the json url https://zactra.com/blackboard/teacher/auth/email/check/numankhan2754#gmail.com
MyHttpHandler myhttp = new MyHttpHandler();
String Newurl = url + "auth/email/check/"+email+"/";
// call MyServiceCall method from Myhttphandler class
String jsonstng = myhttp.MyServiceCall(Newurl);
Log.e(TAG, "Response From URL: " + jsonstng);
if (jsonstng != null) {
try {
JSONObject jsonObject = new JSONObject(jsonstng);
//getting JSON array node
JSONArray jsonArray = jsonObject.getJSONArray("response");
// Looping through all data from json
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject loopjsonObject = jsonArray.getJSONObject(i);
myid = loopjsonObject.getString("response");
// tmp hash map for single contact
HashMap<String, String> mydata = new HashMap<>();
// adding each child node to HashMap key => value
mydata.put("response", myid);
mydatalist.add(mydata);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(StartMainActivity.this, "JSON parsing error", Toast.LENGTH_SHORT).show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(StartMainActivity.this, "Couldn't get json from server. Check LogCat for possible errors!", Toast.LENGTH_SHORT).show();
}
});
}
Response From URL: {"response":"success"}
Json parsing error: Value success at response of type java.lang.String cannot be converted to JSONArray
{"response":"success"} is a JSONObject but you are treating it as JSONArray.
JSON array is always wrapped with []
Example : ["a", "b", "c"] OR something like array of JSONObjects . For example : [{"key":"value"}, {"key","value"}] . Many combinations are possible but most importantly it should start with []
Well
'success'
is not a json array.
an example of a json array is the following
"cars":[ "Ford", "BMW", "Fiat" ]
that is why it cannot be parsed.
the upper example 'cars' array has String values. so String Objects.
In your example you have after the jsonArray a for loop for the jsonArray
for (int i = 0; i < jsonArray.length(); i++)
there you say that you expect JSONObject
so the format that you are waiting is
{"response":[ {"response":"success"},{"response":"success"},{"response":"success"} ]}
which i believe is not the one you finally want :P.
You also create a new HashMap<>() inside the loop. (read about HashMap because your implementation does not support the same key usage ex. cannot have a hashmap with two string objects with same key 'response')
do not make only checks for null checks, do also checks if the string is blank.
First, define the correct format of the response from your service, then the correct implementation for you to capture your data and search the web so that the response to be parsed to an object by the use of a library like jackson.
Regards!
Ps if you want to handle this response,
then
String jsonstng = "{\"response\":\"success\"}";//your service response
String responseValue = "fail";
if (jsonstng != null) {
try {
JSONObject jsonObject = new JSONObject(jsonstng);
if (jsonObject.length() > 0 && jsonObject.has("response")) {
responseValue = jsonObject.getString("response");
}
} catch (final JSONException e) {
//log and handle error
}
}
System.out.println(responseValue);
may be enough
I have JSON returned from my web server in the following form:
{"success":false,"errors":{"username":["Invalid username","Username too short"],"password":["Invalid password"]}}
How can I, in Java, parse the JSON to get the first key and the first value of that key? So in the above case, the output should be:
username
Invalid username
My current code looks like this:
String json = new String(((TypedByteArray) retrofitError.getResponse().getBody()).getBytes());
try {
JSONObject obj = new JSONObject(json);
String success = obj.getString("success");
JSONObject errors = obj.getJSONObject("errors");
// TODO
} catch (JSONException e) {
e.printStackTrace();
}
Perhaps something like this could help you, I'm not completely sure if I understand your problem:
for (final Iterator<String> iter = errors.keys(); iter.hasNext();) {
final String key = iter.next();
try {
final Object value = errors.get(key);
final JSONArray error = (JSONArray) value;
System.out.println(key);
System.out.println(error.get(0).toString());
} catch (final JSONException e) {
// Something went wrong!
}
}