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();
}
Related
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
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 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!
}
}
i want show data with jsonarray
my code activity
params.add(new BasicNameValuePair("id_gadai", id_gadai));
// getting JSON string from URL
String json = jsonParser.makeHttpRequest(URL_GADAI_DETAIL, "GET",
params);
// Check your log cat for JSON reponse
Log.d("Data Gadai Detail: ", json);
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
nama_brg = jObj.getString(TAG_NAMA_BRG);
taksiran = jObj.getString(TAG_TAKSIRAN);
pinjaman = jObj.getString(TAG_PINJAMAN);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
my jsonarray from database
{"data_gadai_detail":[{"id_gadai":"3","nama_brg":"BERLIAN L FINE GOLD
BERSERTIFIKAT NO.SERI JS 006 DTM 24K BRT 10
GRAM","pinjaman":"2000000","taksiran":"4000000","tgl_bts_tebus":"05-May-2013","tgl_bts_lelang":"09-May-2013"}]}
show error :
Error JSONException: No Value For nama_brg
Need help for my problem. thks
Your JSON represents an object with one single field: data_gadai_detail:
{"data_gadai_detail": ...}
The value of this field is an array with a single element:
{"data_gadai_detail": [...]}
This single element is an object with several fields, one of them being nama_brg.
So your code should first get the field data_gadai_detail as an array, take the first element of this array as another JSON object, and finally get the String nama_brg in this object.
You have a JSONArray named "data_gadai_detail" as root, then you need to get the first JSONObject and then you can get the JSONStrings
try this:
JSONObject jObj = new JSONObject(json);
if(jObj != null){
nama_brg = jObj.getJSONArray("data_gadai_detail").getJSONObject(0).getString(TAG_NAMA_BRG);
taksiran = jObj.getJSONArray("data_gadai_detail").getJSONObject(0).getString(TAG_TAKSIRAN);
pinjaman = jObj.getJSONArray("data_gadai_detail").getJSONObject(0).getString(TAG_PINJAMAN);
}
try this one..
JSONObject jObj = new JSONObject(json);
JSONArray arr = jObj.getJSONArray("data_gadai_detail");
for (int i = 0; i < arr.length(); i++) {
JSONObject c = arr.getJSONObject(i);
nama_brg = c.getString(TAG_NAMA_BRG);
taksiran = c.getString(TAG_TAKSIRAN);
pinjaman = c.getString(TAG_PINJAMAN);
}