Get first key and value from JSON object - java

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!
}
}

Related

Get key and value from a JSONObject

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();
}

Get specific value from JSON array using java

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");

Getting JSON values from a .json

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;
}

How to convert string into JSONObject?

I have a string with value abc#xyz.com.
I have to pass this value to server like:
{"email":"abc#xyz.com"}
I am passing value to server like this using okhttp:
Map<String, String> map = new HashMap<>();
map.put("email", email);
new PostMethodWithProgress(login_url, map, this, new Callback()
{
#Override
public void done(String reply)
{
try
{
JSONObject object = new JSONObject(reply);
if (object.getString("status").equals("200"))
{
//Toast Success Message
}
else
{
//Toast Failure Message
}
}
catch (Exception e)
{
Log.e("ASA", "Error is: " + e);
}
}
}).execute();
How do i do it?
You can simply use JSONObject to achieve this
JSONObject jsonObject = new JSONObject();
jsonObject.put("email", "abc#xyz.com");
String result = jsonObject.toString();
Output:
{"email":"abc#xyz.com"}
Use Google Gson convert string to model and model to string easily
ConvertModel convertModel = new Gson().fromJson(reply, ConvertModel .class);
Then you can validate easily
easy way use this code to pass jsonobject as string in okhttp
String jsonString = "";
try {
JSONObject obj = new JSONObject();
obj.put("email", "abc#xyz.com");
obj.put("pwd", "12356");
jsonString = obj.toString();
//out put like this -> {"email":"abc#xyz.com","pwd":"123456"}
Log.d("JsonString__",jsonString);
}catch (Exception e){};
JsonObject is a modifiable set of name/value mappings. Names are unique, non-null strings. Values may be any mix of JSONObject, JSONArray, Strings, Booleans, Integers, Longs, Doubles or NULL.
for your case key is email and value is abc#xyz.com so as I told JsonObject we can put both key and value pair like below -
JsonObject object = new JsonObject();
object.put("email","abc#xyz.com");
If we convert above JsonObject to string then its value would be -
{"email":"abc#xyz.com"}
hope this will help you.
try out this code with your data.
/**
* This method is used to create text size and color code json and store it in json object.
*
* #param textSize text size entered into edit text.
* #param colorOfPreview text color of custom text color.
* #return return json object of created text size and color.
*/
private String createJSONObject(String textSize, int colorOfPreview) {
JSONObject jsonObject = new JSONObject();
try {
// put your values here
jsonObject.put("textSize", textSize);
jsonObject.put("textColor", colorOfPreview);
return jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject.toString();
}

Java get nested JSON object/array

Code used:
jObj = new JSONObject(json);
newJSONString = jObj.getString("payload");
JArray = new JSONArray(newJSONString);
This is what JArray looks like:
[{"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"black"}}]
Now I want to loop through the received times and print their color, how to do this?
What I've tried:
for (int i = 0; i < JArray.length(); ++i) {
JSONObject rec = null;
try {
rec = JArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
android.util.Log.e("print row:", String.valueOf(rec));
}
This just gives me this output:
{"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"black"}}
You are getting this output since your JSON array contains only one JSON object which is - {"06:30:00":{"color":"grey","time_color":"black"},"06:45:00":{"color":"grey","time_color":"black"}}
Before answering your question, I would recommend you to go through JSON syntax. It will help you understand your question and answer effectively.
Coming back to your question, in order to get "color" field from your nested JSON:
Traverse through keys in your JSON object. In your case these are -
"06:30:00" , "06:45:00". You can google out solution to traverse
through keys in JSON object in java.
Get nested object associated with given key(time) - you can use
getJSONObject() method provided by Json library for this.
Get "color" field from json object - you can use optString() or
getString() methods provided by Json library for this- depending
upon whether your string is mandatory or optional.
Here is working solution in java for your problem:
public static void getColor(JSONObject payloadObject) {
try {
JSONArray keys = payloadObject.names();
for (int i = 0; i < keys.length(); i++) {
String key = keys.getString(i); // Here's your key
JSONObject value = payloadObject.getJSONObject(key); // Here's your value - nested JSON object
String color = value.getString("color");
System.out.println(color);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Please note, it is considered that object you receive as payload is a JSON object.
Hope this helps.
Thanks.
Use Keys() method which return Iterator<String> so that it will be easy for iterating every nested JSON
for (int i = 0; i < JArray.length(); ++i) {
try {
JSONObject rec = JArray.getJSONObject(i);
Iterator<String> keys = rec.keys();
while(keys.hasNext()) {
String key1 = keys.next();
JSONObject nested = rec.getJSONObject(key1); //{"color":"grey","time_color":"black"}
//now again same procedure
Iterator<String> nestedKeys = nested.keys();
while(nestedKeys.hasNext()) {
String key2 = nestedKeys.next();
System.out.println("key"+"..."+key2+"..."+"value"+"..."+nested.getString(key2);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
android.util.Log.e("print row:", String.valueOf(rec));
}

Categories

Resources