Java get nested JSON object/array - java

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

Related

How to return a from json converted array in java?

The following code works fine(!), i wnat to moved it into a own function, but i cant return the from json converted Array (last line). What im doing wronng?
public Array jsonToArray(String json) {
JSONObject myjson = null;
try {
myjson = new JSONObject(json);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray the_json_array = null;
try {
the_json_array = myjson.getJSONArray("profiles");
} catch (JSONException e) {
e.printStackTrace();
}
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = null;
try {
another_json_object = the_json_array.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
arrays.add(another_json_object);
}
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
return Array jsons;
}
I think the Problem is the Type, but im completely new in JAVA... Im getting the error: 'Not a statement'. What is the meaning and the Solution?
public JSONObject[] jsonToArray()
As well as
return jsons;
Or, why not return the ArrayList<JSONObject>, why bother with another conversion?
Though, ideally, returning an actual JSONArray object instead of a Java array of JSONObject makes more sense.
Such as
return myjson.getJSONArray("profiles");
Or, one step further, actually parsing out the values of the JSON you want into your own Java classes?
You should do:
return jsons;
And also correct the return type, you have Array there, I don't see that type defined anywhere in your code, and there is no such type in java, you probably wanted JSONObject[], so the first line of the method will be:
public JSONObject[] jsonToArray(String json) {

Get first key and value from JSON object

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

Unable to set json string to TextView in onPostExecute in asyncTask

The problem that I'm facing right now is I simply want to set the string data from a json array in onPostExecute(). I skeemed through many tutorials on it, however, I am unable to set the Text that resides in the MainActivity. I've added the sample code below . I wonder if the data is wrong .
#SuppressWarnings("unchecked")
protected void onPostExecute(JSONObject jsonobject) {
try {
jsonarray = jsonobject.getJSONArray("grape");
outerjson = jsonarray;
String ids = jsonobject.optString("id");
String tpes = jsonobject.optString("type");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
String str = "";}
// Step 3.
map1 = new HashMap<String, String>();
// this is the last step 4.
try {
JSONArray jArray = new JSONArray(str);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = null;
json = jArray.getJSONObject(i);
map1.put("id", json.getString("id"));
map1.put("type", json.getString("type"));
}
result.setText(jsonarray.toString());
///set the json in here
}catch (JSONException e) {}
} catch (JSONException e) {}
progressDialog.dismiss();
}
Not enough information, but I will try:
Make your code cleaner by using a container entity: MyData data = gson.fromJson(jsonobject, MyData.class).
Do not ignore exceptions
Make sure you are calling result.setText(string); within a main UI thread
Follow these 3 steps and, find the error, you will.

Android JSON Parsing And Conversion

Good morning.
I am trying to parse JSON data into a string but I think I'm doing something wrong: here is the section.
private void read_JSON()
{
String JSON;
JSONObject jso3 = new JSONObject(JSON);
for (int i=0; i < jso3.length(); i++)
{
try
{
String name = jso3.getString("Nombre");
String surname = jso3.getString("Apellidos");
String date = jso3.getString("Año_nacimiento");
String child_names = jso3.getString("Nombres_Hijos");
}catch (JSONException e)
{
e.printStackTrace();
}
}
jso3.toString(JSON);
}
I created the JSON within the MainActivity.java, it's not on a separate file.
Here is the code of the JSON creation:
private void create_JSON()
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jso.toString();
I have no doubts that the JSON is correctly created, I just need help in understanding how do I parse it and convert it into a String.
I would be very grateful if you could point out to me the flaws in my programming.
Mauro.
Try this..
Your response like below
{ ==> JSONObject
"Año_nacimiento": 1990, ==> String from JSONObject
"Nombres_Hijos": [ ==> JSONArray
"Blur", ==> Directly from JSONArray
"Clur"
],
"Apellidos": "Garcia",
"Nombre": "Miguel"
}
To parse the JSON use below code:
JSONObject jso3 = new JSONObject(output);
String name = jso3.getString("Nombre");
String surname = jso3.getString("Apellidos");
int date = jso3.getInt("Año_nacimiento");
JSONArray menuObject = jso3.getJSONArray("Nombres_Hijos");
for(int i=0;i<menuObject.length;i++){
System.out.println(menuObject.getString(i));
}
Use the following options while parsing JSON to avoid common error.
JSONObject jso3 = new JSONObject(output);
String name = jso3.optString("Nombre",""); // here default value is blank ("")
String surname = jso3.optString("Apellidos",null);// here default value is null
int date = jso3.getInt("Año_nacimiento",0); // here default value is ZERO (0)
JSONArray menuObject = jso3.getJSONArray("Nombres_Hijos");
for(int i=0;i<menuObject.length;i++){
System.out.println(menuObject.getString(i));
}
Using opt option you can set default return value. Event if that tag not available in JSON data you will get default value.
This works for me better than GSON lib.
Try this.
String apellidos = jso.getString("Apellidos");
System.out.println(apellidos);
int str2 = jso.getInt("Año_nacimiento");
System.out.println(str2);
String nombre = jso.getString("Nombre");
System.out.println(nombre);
JSONArray array = jso.getJSONArray("Nombres_Hijos");
for(int i = 0; i < array.length(); i++){
System.out.println(array.get(i));
}
First at all, you seem to ignore Strings created in read_JSON, but i assume you do this to avoid pasting here too much code.
Problem is this line:
String child_names = jso3.getString("Nombres_Hijos");
Because fields Nombres_Hijos is JsonArray, not String. To read it use:
JSONArray jsa = jso3.getJSONArray("Nombres_Hijos");
Now all depands what you need to do later with this data.
Easiest case would be:
String names = jsa.toString(); //["Blur","Clur"]
private void read_JSON(String json)
{
JSONObject jObject= new JSONObject(json);
JSONArray jso3= new JSONArray(jObject.getString("Nombres_Hijos"));
for (int i=0; i < jso3.length(); i++)
{
try
{
String name = jso3.getString("Nombre");
String surname = jso3.getString("Apellidos");
String date = jso3.getString("Año_nacimiento");
String child_names = jso3.getString("Nombres_Hijos");
}catch (JSONException e)
{
e.printStackTrace();
}
}
jso3.toString(JSON);
}
try{
String JSON ;
JSONObject jso3 = new JSONObject(JSON);
JSONArray menuObject = new JSONArray(jObject.getString("array_inside_json"));
for(int i=0;i<menuObject.length;i++){
name=jObject.getString("inside"));
}
}catch(Exception e){
}
refer this link for more info

how to deserialize json to a dictionary or keyvaluepair?

I have to deserialize a JSON object like this
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{"id":0, "Name":"an Object"}, "Value":true}]
I know how to deserialize arrays and singleobjects or variables. but I'm in the blue about dictionaries.
I'm using the following to read an array
NetworkEvent n = (NetworkEvent) evt;
byte[] data = (byte[]) n.getMetaData();
AnObject[] anObject= null;
try {
JSONArray json = new JSONArray(new String(data, "UTF-8"));
anObject= AnObject.getAnObjects(json);
} catch (Exception ex) {
ex.printStackTrace();
}
The final code solution:
Object[] objects= new Object[json.length()];
for (int i = 0; i < json.length(); ++i) {
Key key= null;
Value value = null;
try {
JSONObject keyValuePair = json.getJSONObject(i);
key= Key.getKey(keyValuePair.getJSONObject("Key"));
value= keyValuePair.getBoolean("Value");
} catch (JSONException ex) {
ex.printStackTrace();
}
Object object= new object();
object.setKey(key);
object.setValue(value);
Objects[i] = object;
}
return objects;
What you have there is not a JSON object. It is an array of JSON objects, and therefore your current code should work.
I think that your "problem" is that you are using the wrong terminology.
This is an attribute or name/value pair:
"id":0
This is an object:
{"id":0, "Name":"an Object"}
This is also an object:
{"Key":{"id":0, "Name":"an Object"}, "Value":true}
This is an array (of objects)
[{"Key":{"id":0, "Name":"an Object"}, "Value":true},
{"Key":{"id":0, "Name":"an Object"}, "Value":true}]
For more details, refer to the json.org site.
Try the Jackson library.

Categories

Resources