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]
Related
Im trying to make a JAVA application that makes a json file with the data that i send, but when i send new data, the last data the data is just replaced
the first method called
az.addUser("John", "10", "star");
the JSON
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
}
second method called
az.addUser("Kevin", "20", "energy");
The JSON Expected
{
"user" : {
"name": "john",
"score": "10",
"type": "star"
}
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "energy"
}
}
the REAL JSON
{
"user" : {
"name" = "Kevin",
"score" = "20",
"type" = "Energy"
}
}
The Method
public void addUser(String name, String score, String type){
FileWriter wf = new FileWriter("exit.json");
JSONObject json;
JSONObject jsonInternal = new JSONObject();
jsonInternal.put("name", name);
jsonInternal.put("score", score);
jsonInternal.put("type", type);
json = new JSONObject();
json.put("user", jsonInternal);
wf.write(json.toJSONString());
wf.close();
}
You need to write a JSON array, not a JSON object. The code below is strictly pseudocode, as I do not know which library JSONObject comes from.
import java.io.FileWriter;
import java.io.IOException;
public class UserListWriter {
private String filename;
private JSONArray usersJson;
public UserListWriter(String filename) {
this.filename = filename;
this.usersJson = new JSONArray();
}
public UserListWriter addUser(String name, int score, String type) {
JSONObject userJson = new JSONObject();
userJson.put("name", name);
userJson.put("score", score);
userJson.put("type", type);
usersJson.put(userJson);
return this;
}
public UserListWriter write() throws IOException {
FileWriter wf = new FileWriter(this.filename);
wf.write(usersJson.toJSONString());
wf.close();
return this;
}
public static void main(String[] args) {
try {
new UserListWriter("exit.json")
.addUser("John", 10, "star")
.addUser("Kevin", 20, "energy")
.write();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Theoretical output:
[{
"name": "John",
"score": 10,
"type": "star"
}, {
"name": "Kevin",
"score": 20,
"type": "energy"
}]
I am trying to retreive customer object from my rest api. I generated the api using spring data jpa. I have used volley to retrive the information from the api. I can't tell what i did wrong. As i am new to android i don't have much idea. can some one help me to parse the customer object from my Json api.
my api looks like this:
{
"_embedded": {
"customers": [
{
"firstName": "Alexander",
"lastName": "arnold",
"email": "trentarnold#liverpool.com",
"password": "cornertakenquickly",
"_links": {
"self": {
"href": "http://localhost:8080/api/customers/1"
},
"customer": {
"href": "http://localhost:8080/api/customers/1"
}
}
},
{
"firstName": "test",
"lastName": "tester",
"email": "dulalsujan911#gmail.com",
"password": "12345678",
"_links": {
"self": {
"href": "http://localhost:8080/api/customers/2"
},
"customer": {
"href": "http://localhost:8080/api/customers/2"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/customers{?page,size,sort}",
"templated": true
},
"profile": {
"href": "http://localhost:8080/api/profile/customers"
}
},
"page": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 0
}
}
my code looks like this i am using volley :
// connects to the api and stores the retrived JSON values in the respective list
public void connectToApi(){
// initialize lists
emailList = new ArrayList<>();
passwordList = new ArrayList<>();
final String BASE_URL ="http://192.168.1.67:8080/api/customers";
// final String BASE_URL ="http://10.0.2.2:8080/api/customers";
// creating a request ques for HTTP request
RequestQueue requestQueue = Volley.newRequestQueue(this);
// Setting HTTP GET request to retrieve the data from the SERVER
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET,BASE_URL
,null
, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("customers");
for(int i=0; i<jsonArray.length();i++){
JSONObject customer = jsonArray.getJSONObject(i);
emailList.add(customer.getString("email"));
passwordList.add(customer.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
} , new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("REST error",error.toString() );
}
}
);
requestQueue.add(objectRequest);
}
Do this :
#Override
public void onResponse(JSONObject response) {
try {
JSONObject json = new JSONObject(response);
JSONObject json_embedded = json.getJSONObject("_embedded");// need to access JSONObject("_embedded")
JSONArray jsonArray = json_embedded.getJSONArray("customers"); // then get JSONARRAY
for(int i=0; i<jsonArray.length();i++){
JSONObject customer = jsonArray.getJSONObject(i);
emailList.add(customer.getString("email"));
passwordList.add(customer.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
NOTE : your json array (customers) is in _embedded that's why
it is showing exception.
You need to access first to _embedded object.
try {
JSONObject embedded = response.getJSONObject("_embedded");
JSONArray jsonArray = embedded.getJSONArray("customers");
for(int i=0; i<jsonArray.length();i++){
JSONObject customer = jsonArray.getJSONObject(i);
emailList.add(customer.getString("email"));
passwordList.add(customer.getString("password"));
}
} catch (Exception e) {
e.printStackTrace();
}
Recently, I tried to code a list of linkman. I want to obtaining local data file(City.json) and parsing into listView. However ,the data from JsonObject always null. Help me please. I'm a Newbie. Thanks in advance.
the code under:
City.json
{
// "state": 1,
"datas": [
{
"id": "820",
"name": "安阳",
"sortKey": "A"
},
{
"id": "68",
"name": "安庆",
"sortKey": "A"
},
{
"id": "1269",
"name": "鞍山",
"sortKey": "A"
},
{
"id": "22",
"name": "蚌埠",
"sortKey": "B"
},
{
"id": "1372",
"name": "包头",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
},
{
"id": "2419",
"name": "北京",
"sortKey": "B"
},
{
"id": "649",
"name": "保定",
"sortKey": "B"
},
{
"id": "1492",
"name": "宝鸡",
"sortKey": "B"
}
]
}
AppFileReader.java
package me.sitinglin.administrator.wecharlinkmantest;
import android.content.Context;
import android.content.res.AssetManager;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
/**
* Created by Administrator on 2016/10/12.
*/
public class AppJsonFileReader {
public static String getJson(Context context, String fileName){
StringBuilder builder = new StringBuilder();
AssetManager manager = context.getAssets();
try {
InputStream stream = manager.open(fileName);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line = null;
while((line = bufferedReader.readLine())!=null){
builder.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
// Log.i("abc", builder.toString());
return builder.toString();
}
public static List<City> setData(String str){
List<City> list = new ArrayList<>();
City city ;
try {
JSONObject result = new JSONObject(str);
JSONArray array = result.getJSONArray("datas");
// JSONArray array =new JSONArray(result);
int len = array.length();
Log.i("len", array.toString());
for (int i = 0; i <len ; i++) {
JSONObject object = array.optJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
}
}
this my context of logcat
Try this:
try {
JSONObject result = new JSONObject(str);
JSONArray jsonArray = result.getJSONArray("datas");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
city = new City();
city.setId(object.optString("id"));
city.setName(object.optString("name"));
city.setSortKey(object.optString("sortKey"));
list.add(city);
}
} catch (JSONException e) {
e.printStackTrace();
}
Log.i("lll", list.toString());
return list;
You should go with following code :
JSONObject jobj = new JSONObject(str);
if(jobj.has("datas")){
JSONArray jsonArray = jobj.getJSONArray("datas");
List<City> list = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jdataObj = jsonArray.getJSONObject(i);
City city = new City();
city.setId(jdataObj.getString("id"));
city.setName(jdataObj.getString("name"));
city.setSortKey(jdataObj.getString("sortKey"));
list.add(city);
}
} else {
Log.e("Json","Json has no datas key.")
}
Hope this will help you.
I found 3 solution to solve this.i will list 3 things that i've solved below and one of the 3 solutions may helped you.
there are three point which one of three point maybe help U :
1. checking out the [local file name] of JSON;
2. checking out variale is "public " or "private"..;
3.checking out some Json method whether you are uesing correct?
Aha...
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
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);
}
}
}