This is Json file.
{
"paging": {
"next_offset": 100,
"total": 247,
"limit": 100
},
"body_stats": [
{
"weight": 208.0,
"id": "13500547638911",
"date": "2012-10- 12T15:12:50Z",
"user_id": "13499829320503",
"bmr": 2723.328,
"bmi": 28.2067901234568
},
{
"resting_heart_rate": 65.0,
"weight": 135.0,
"id": "1b5kegg00 00js2p5pfmg000000",
"date": "2013-04- 15T00:44:12Z",
"user_id": "13589643116210",
"girths": {
"abdomen": 30.0,
"waist": 30.0
}
}
]
}
I want to read values from this json,
try{
Object obj = parser.parse(new FileReader("D:/jdemo.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray companyList = (JSONArray)jsonObject.get("body_stats");
Iterator<Object> iterator = companyList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
Output:
{
"id": "13500547638911",
"bmr": 2723.328,
"weight": 208.0,
"bmi": 28.2067901234568,
"user_id": "13499829320503",
"date": "2012-10-12T15:12:50Z"
},
{
"id": "1b5kegg0000js2p5pfmg000000",
"weight": 135.0,
"girths": {
"abdomen": 30.0,
"waist": 30.0
},
"user_id": "13589643116210",
"date": "2013-04-15T00:44:12Z",
"resting_heart_rate": 65.0
}
But I want to read "girths"{" ",""} from this how can I read girths{} value?
This is an approach.
JsonElement jsonElement = new JsonParser().parse(new FileReader("D:/jdemo.json"));
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("body_stats");
for(JsonElement body_stats : jsonArray) {
JsonElement girths = body_stats.getAsJsonObject().get("girths");
if(griths !=null) {
//The logic
}
}
"girths" should be another JSONObject, so I guess
.getJSONObject(2).get("girths");
on your JSONArray
try{
Object obj = parser.parse(new FileReader("D:/jdemo.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray companyList = (JSONArray)jsonObject.get("body_stats");
Iterator<JSONObject> iterator = companyList.iterator();
while (iterator.hasNext()) {
JSONObject jsonObject = iterator.next();
Object object = jsonObject.get("girths");
if(object != null){
JSONObject girths = (JSONObject )object ;
System.out.println(girths);
}
}
}
Related
How I can get the "fields" objects 0,1,2,3,4 & only the "name" object string of every object using JSONOBJECT
[
{
"name": "Bank1",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"3": {
"name": "Full Name",
"slug": "full-name",
"type": "input"
}
},
"status": "Active"
},
{
"name": "Bank2",
"fields": {
"0": {
"name": "Email",
"slug": "email",
"type": "input"
},
"1": {
"name": "City",
"slug": "city",
"type": "input"
},
"2": {
"name": "Screenshot",
"slug": "screenshot",
"type": "file"
},
"4": {
"name": "Submitted Date",
"slug": "submitted-date",
"type": "calendar"
}
},
"status": "Active"
}
]
& this is what I try to done
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String p_name = jsonObject.getString("name");
JSONObject jo = jsonObject.getJSONObject("fields");
String j1 = jo.getString("0");
if (!j1.isEmpty()){
JSONObject jo1 = jo.getJSONObject("0");
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}}catch block...
but the problem is, it gives me value of the object null like [value 4 is null] cuz there is no object for 4 in the first object of fields. please help me solve this prob, appreciate your answers thankyou :)
You can use keys() iterator of json object & loop on it using while (keys.hasNext())
For your example, it would look something like this:
private void parseJson(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
Iterator<String> keys = jo.keys();
while (keys.hasNext()) {
String key = keys.next();
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
Log.d("Field1.", f_name1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
There are some problems with get all keys properly in my IDE/JDK11, so I decided to loop over an ArrayList, basing on #MayurGajra solution, ex:
private static List<List<String>> parseJson(String response) throws JSONException {
JSONArray jsonArray = new JSONArray(response);
List<List<String>> result = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONObject jo = jsonObject.getJSONObject("fields");
List<Object> list = new ArrayList<>();
jo.keys().forEachRemaining(list::add);
List<String> subList = new ArrayList<>();
for (Object o : list) {
String key;
if (isString(o))
key = (String) o;
else
continue;
JSONObject jo1 = jo.getJSONObject(key);
String f_name1 = jo1.getString("name");
subList.add(f_name1);
}
result.add(subList);
}
return result;
}
private static boolean isString(Object o) {
try {
String result = (String) o;
} catch (ClassCastException e) {
return false;
}
return true;
}
The result obtained after processing the above json is as follows:
[[Email, City, Screenshot, Full Name], [Email, City, Screenshot, Submitted Date]]
but it have not to be a List of Lists ;)
-- edit --
To get only first list of elements labeled "name":
try {
System.out.println(parseJson(yourJsonAsString).get(0).toString());
} catch (JSONException e) {
System.out.println("JSONException:" + e.getMessage());
}
The result of above is:
[Email, City, Screenshot, Full Name]
how to save data from our textfields. For example i want to get this:
[
{
"Patient": {
"name": "John",
"surname": "Cena"
}
},
{
"Patient2": {
"name": "Roger",
"surname": "Federer"
}
}
]
And it was my try:
JSONObject obj = new JSONObject();
obj.put("imie", field1.getText());
obj.put("nazwisko", field2.getText());
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(obj.toJSONString());
Data.write(obj1.toJSONString());
} catch (IOException e1) {
e1.printStackTrace();
}
but i dont get "Patient2" and it overwriting my first patient if i press save button instead of add new one.
You should be using JSONArray to store several JSONObject instances:
// build object
JSONObject obj = new JSONObject();
obj.put("name", field1.getText());
obj.put("surname", field2.getText());
// build "patient"
JSONObject patient = new JSONObject();
patient.put("patient", obj);
// build another object
JSONObject obj1 = new JSONObject();
obj1.put("name", "Roger");
obj1.put("surname", "Federer");
// build another patient
JSONObject patient1 = new JSONObject();
patient1.put("patient1", obj1);
// create array and add both patients
JSONArray arr = new JSONArray();
arr.put(patient);
arr.put(patient1);
try (FileWriter Data = new FileWriter("Data.JSON")) {
Data.write(arr.toString(4)); // setting spaces for indent
} catch (IOException e1) {
e1.printStackTrace();
}
This code produces JSON:
[
{
"patient": {
"surname": "Doe",
"name": "John"
}
},
{
"patient1": {
"surname": "Federer",
"name": "Roger"
}
}
]
I am trying to update the remote JSON values using Volley for Android. Problem is that the code below completely overrides the whole JSON object.
File is located here: https://api.myjson.com/bins/kubxi
Original JSON file looks like this:
{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 1,
"action_2": 2,
"action_3": 3
}
]
},
{
"id": 2,
"name": "Name Two",
"actions": [
{
"action_1": 4,
"action_2": 5,
"action_3": 6
}
]
}
]
}
Java code
private void sendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
final JSONObject jsonObject = new JSONObject();
String url ="https://api.myjson.com/bins/kubxi"; // Remote JSON file
try {
jsonObject.put("action_1", 123);
jsonObject.put("action_2", 456);
jsonObject.put("action_3", 789);
} catch (JSONException e) {
Log.d("Exception", e.toString());
}
JsonObjectRequest putRequest = new JsonObjectRequest(Request.Method.PUT, url, jsonObject,
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Error.Response", error.toString());
}
}
)
{
#Override
public Map<String, String> getHeaders()
{
Map<String, String> headers = new HashMap<>();
headers.put("Accept", "application/json");
headers.put("Content-Type", "application/json");
return headers;
}
#Override
public byte[] getBody() {
try {
Log.i("JSON", jsonObject.toString());
return jsonObject.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
};
queue.add(putRequest);
}
After using this code, JSON file looks like this:
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
I was expecting for the code to only update the values on action_1, action_2 and action_3 from 1, 2, 3 to 123, 456, 789.
I want the JSON file to look like that after running the code:
{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
]
},
{
"id": 2,
"name": "Name Two",
"actions": [
{
"action_1": 123,
"action_2": 456,
"action_3": 789
}
]
}
]
}
Suggestions will be appreciated!
To update particular value in json file ,you can do like this:
Firstly take your original json in String :
String jsonString ="{
"females": [
{
"id": 1,
"name": "Name One",
"actions": [
{
"action_1": 1,
"action_2": 2,
"action_3": 3
}
]
}
]
}";
Next ,pass this String in JsonObject:
JSONObject jObject = new JSONObject(jsonString);//passing string to jsonobject
JSONArray jsonArray = jObject.getJSONArray("females");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
JSONArray jsonObject= object.getJSONArray("actions"); //getting action
array
for (int j = 0; j < jsonObject.length(); j++) {
JSONObject object1 = jsonObject.getJSONObject(j);
object1.put("action_1", 123); //here you are putting value to action_1
object1.put("action_2", 456);
object1.put("action_3", 789);
}
}
and then send this jsonObject to your server.
I'm getting JSON data from a url and I want to show the data on my website. I am successfully showing all JSON data except JSON Hierarchy (JSON Object) data. I am able to access JSONArray person and error data. But, I am not able to access hierarchy (JSON Object) updated data.
I want to access updated.time.
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ParseException;
public class ParseJson1 {
public static void main(String[] args) {
String url = "http://freemusicarchive.org/api/get/genres.json?api_key=60BLHNQCAOUFPIBZ&limit=2";
/*
{
"person": [
{
"name": "John",
"city": "Mumbai"
},
{
"name": "Rahul",
"city": "Delhi"
},
{
"name": "Sanjana",
"city": "Amritsar"
},
{
"name": "Anjali",
"city": "Hyderabad"
},
{
"name": "Mukund",
"city": "Bangalore"
},
{
"name": "Raunak",
"city": "Patna"
}
],
"updated": {
"time": "14:17:48",
"date": "2016-04-10"
},
"error": "2353"
}
*/
try {
String genreJson = IOUtils.toString(new URL(url));
JSONObject genreJsonObject = (JSONObject) JSONValue.parseWithException(genreJson);
// get the error
System.out.println(genreJsonObject.get("error"));
//Get Array Values
JSONArray genreArray = (JSONArray) genreJsonObject.get("person");
// get the first genre
JSONObject firstGenre = (JSONObject) genreArray.get(0);
System.out.println(firstGenre.get("name"));
// get the Second
JSONObject firstGenre = (JSONObject) genreArray.get(1);
System.out.println(firstGenre.get("name"));
// get the third
JSONObject firstGenre = (JSONObject) genreArray.get(2);
System.out.println(firstGenre.get("city"));
} catch (IOException | ParseException e) {
e.printStackTrace();
}
}
}
This json Result appears what you got from your api URL . Right ??
{
"person":[
{
"name":"John",
"city":"Mumbai"
},
{
"name":"Rahul",
"city":"Delhi"
},
{
"name":"Sanjana",
"city":"Amritsar"
},
{
"name":"Anjali",
"city":"Hyderabad"
},
{
"name":"Mukund",
"city":"Bangalore"
},
{
"name":"Raunak",
"city":"Patna"
}
],
"updated":{
"time":"14:17:48",
"date":"2016-04-10"
},
"error":"2353"
}
Now Here is a Code how to Iterate or parse your json Object. I Suppose that above Result json is stored in a String Variable String genreJson as per Your Code.
Here I wrote a method to solve your Problem. You may take a reference of it and may try your own code.
public void testYourJSON(String genreJson){
JSONParser parser=new JSONParser(); //parser used to parse String to Correct Json format.
JSONObject obj_ComplexData = (JSONObject) parser.parse(genreJson); // Now Your String Converted to a JSONObject Type.
//person tag Array Data is fetched and Stored into a JSONArray Object.
JSONArray obj_arrayPersonData = (JSONArray) parser.parse(obj_ComplexData.get("person").toString());
for (Object person : obj_arrayPersonData ) { //Iterate through all Person Array.
System.out.println(person.get("name"));
System.out.println(person.get("city"));
}
//Select "updated" Tag Json Data.
JSONObject obj_Updated = (JSONObject) parser.parse(obj_ComplexData.get("updated").toString());
System.out.println(obj_Updated.get("time")); //display time tag.
System.out.println(obj_Updated.get("date")); //display date tag.
System.out.println(obj_Updated.get("error")); //display Your Error.
}
Try this
public static String[] getInfo(String url)
{
String result=//I am assuming your json response is in result
String[] titles=null;
try {
JSONObject jsonObject=new JSONObject(result);
JSONObject temp=null;
JSONArray jsonArray=jsonObject.getJSONArray("person");
int length=jsonArray.length();
person=new String[length];
for (int i=0;i<length;i++){
temp= (JSONObject) jsonArray.get(i);
titles[i]=temp.getString("name")+temp.getString("city");
}
} catch (JSONException e) {
e.printStackTrace();
}
return titles;
}
This works fine, if you face any problem write in comments.
Happy coding!!
Here i want to fetch the data from the json, but i am getting only first two objects value (25, 44) but the ids are 50,60 . I don't know whats wrong with this code.
Below is my response from the server:
{
"product": {
"25": {
"training": "First Name",
"taken": null,
"date": "1386737285",
"body":"http://abc.xyz.in/video1.mp4",
"image": "http://abc.xyz.in/video1.jpg"
},
"44": {
"training": "Second Name",
"taken": null,
"date": "1389951618",
"body":"http://abc.xyz.in/video2.mp4",
"image":"http://abc.xyz.in/video2.jpg"
},
"50": {
"training": "Third Name",
"taken": null,
"date": "1389971004",
"body":"http://abc.xyz.in/video3.mp4",
"image": "http://abc.xyz.in/video3.jpg"
},
"60": {
"training": "Fourth Name",
"taken": null,
"date": "1390003200",
"body": "http://abc.xyz.in/video4.mp4",
"image": "http://abc.xyz.in/video4.jpg"
}
}
}
Here is the code for fetching data from json:
public String[] getDataFromResponse(String jsonProfileResponse,String secondParam,
String attributeName ) {
String[] attributeValue = null;
try {
json = new JSONTokener(jsonProfileResponse).nextValue();
if (json instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) json;
JSONObject jObj = jsonObject.getJSONObject(secondParam);
System.out.println(jObj);
Iterator<?> keys = jObj.keys();
List<String> listitems = new ArrayList<String>();
List<String> nids = new ArrayList<String>();
while (keys.hasNext()) {
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys
.next()));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
attributeValue = listitems.toArray(new String[0]);
trainingId = nids.toArray(new String[0]);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
return attributeValue;
}
Thanks for the considering...
Inside the hasNext you call twice keys.next()
So, instead of
nids.add(String.valueOf(keys.next()));
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(keys.next()));
you have to do
String currentKey = String.valueOf(keys.next());
nids.add(currentKey);
JSONObject jsonObj = jObj.getJSONObject(currentKey);
String key="";
while (keys.hasNext()) {
key= keys.next()
JSONObject jsonObj = jObj.getJSONObject(String.valueOf(key));
nids.add(key));
System.out.println(jsonObj);
listitems.add(jsonObj.getString(attributeName));
}
use of key.next() twice is problem
because in JSONObject, the order of the keys is undefined.
#see: http://developer.android.com/reference/org/json/JSONObject.html#keys%28%29
try to sort your data on server, then response it in JSONArray