I am creating json string but unable to give tag to JSONObject in nested json string.
Here is what I want
"User": [
{
"User1": {
"name": "name1",
"Address": "add1",
"user_detail": {
"Qualification": B.E,
"DOB": 11/2/1990,
}
}
},
{
"User2": {
"name": "name2",
"Address": "add2",
"user_detail": {
"Qualification": B.E,
"DOB": 11/2/1990,
}
}
}
}
]
And I have managed to get until here
{"User":[{"name":"name1","Address":"Add1"}, {"Qualification": "B.E", "DOB":"11/12/1990"}]}
But I am failed to add tag for JSONObject both for USer and user_details
Here is my code
try {
user = new JSONObject();
user.put("name", "name1");
user.put("Address", "B.E");
} catch (JSONException je) {
je.printStackTrace();
}
try {
userObj = new JSONObject();
userObj.put("User1", user);
jsonArray = new JSONArray();
jsonArray.put(user);
} catch (JSONException j) {
j.printStackTrace();
}
}
try {
users = new JSONObject();
users.put("User", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
The main thing is I am do not know, how to give tags to JSONObject.
You could just pass the desired JSON String to the JSONObject constructor to do the job. Take a look here
Current String Contain JSONArray of JSONObject's instead of JSONObject as root element. You can create Current Json String in java as:
JSONArray jsonArray = new JSONArray();
// User1 JSONObjects
user = new JSONObject();
user.put("name", "name1");
user.put("Address", "B.E");
user_obj_one = new JSONObject();
user_obj_one.put("User1",user);
//...same for User2...
...
user_obj_two = new JSONObject();
user_obj_two.put("User2",user_two);
//put in final array :
jsonArray.put(user_obj_one);
jsonArray.put(user_obj_two);
//....
Related
I'm creating an app to get posts from a web server, and i'm getting a jsonarray to object error I'm new to android development and tutorials i see the JsonArray is named before, so it'd be array of dogs, and then inside that would have breed and name and so on, mines not named.
the code i have is
public class GetData extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String current = "";
try{
URL url;
HttpURLConnection urlConnection = null;
try{
url = new URL(JSONURL);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
int data = isr.read();
while(data !=-1){
current += (char) data;
data = isr.read();
}
return current;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
if(urlConnection !=null){
urlConnection.disconnect();;
}
}
}catch (Exception e){
e.printStackTrace();
}
return current;
}
#Override
protected void onPostExecute(String s) {
try{
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("");
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Displaying the results
ListAdapter adapter = new SimpleAdapter(
MainActivity.this,
postList,
R.layout.item,
new String[]{"name", "post"},
new int[]{R.id.textView, R.id.textView2});
lv.setAdapter(adapter);
}
}
the json code i'm trying to parse is
[
{
"0": "2",
"id": "2",
"1": "anon",
"name": "anon",
"2": "goodbye people of skivecore",
"post": "goodbye people of skivecore",
"3": "38.751053",
"lat": "38.751053",
"4": "-90.432915",
"lng": "-90.432915",
"5": "",
"ip": "",
"6": "6.204982836749738",
"distance": "6.204982836749738"
},
{
"0": "1",
"id": "1",
"1": "anon",
"name": "anon",
"2": "hello people of skivecore",
"post": "hello people of skivecore",
"3": "38.744453",
"lat": "38.744453",
"4": "-90.607986",
"lng": "-90.607986",
"5": "",
"ip": "",
"6": "9.280600590285143",
"distance": "9.280600590285143"
}
]
and stacktrace message
2021-04-28 23:45:02.156 20352-20352/com.skivecore.secrets W/System.err: org.json.JSONException: Value [{"0":"2","id":"2","1":"anon","name":"anon","2":"goodbye people of skivecore","post":"goodbye people of skivecore","3":"38.751053","lat":"38.751053","4":"-90.432915","lng":"-90.432915","5":"","ip":"","6":"6.204982836749738","distance":"6.204982836749738"},{"0":"1","id":"1","1":"anon","name":"anon","2":"hello people of skivecore","post":"hello people of skivecore","3":"38.744453","lat":"38.744453","4":"-90.607986","lng":"-90.607986","5":"","ip":"","6":"9.280600590285143","distance":"9.280600590285143"}] of type org.json.JSONArray cannot be converted to JSONObject
You should use like below
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
}
I think here is the issue JSONObject jsonObject = new JSONObject(s); as I can see your response is a JSONArray because it has [ and ] at the beginning and the end.
So, I think this would be more appropriate.
try{
JSONArray jsonArray = jsonObject.getJSONArray(s);
for(int i = 0; i<jsonArray.length();i++){
JSONObject jsonObject1= jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
}
please usding gson library To use jasonArray And JsonObject Easley
1). https://github.com/google/gson
2). libraby import then use
https://www.jsonschema2pojo.org/
for your jsonArray to Model class
Then Use jsonArray
Use this instead....
try {
JSONArray jsonArray = new JSONArray(s);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
namey = jsonObject1.getString("name");
post = jsonObject1.getString("post");
//put to hashmap
HashMap<String, String> posts = new HashMap<>();
posts.put("name", namey);
posts.put("post", post);
postList.add(posts);
}
} catch (JSONException e) {
e.printStackTrace();
How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.
I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object
I have to frame a json like the following while making a json request:
{
"method": "version",
"data": {
"username": "korea",
"order_point_of_contact": {
"shipment_version": "1",
"testimonial_version": "3",
"point_of_contact_version": "2"
}
}
}
I use the following code to frame it:
JSONObject data = new JSONObject();
JSONObject pointofContact = new JSONObject();
JSONObject jsonObject = new JSONObject();
try {
data.put("username", "korea");
jsonObject.put("method", "version");
jsonObject.put("data", data);
jsonObject.put("order_point_of_contact", pointofContact);
jsonObject.put("shipment_version", "1");
jsonObject.put("testimonial_version", "3");
jsonObject.put("point_of_contact_version", "2");
} catch (JSONException e) {
e.printStackTrace();
}
But the problem is that it doesn't frame the desired json. What is the error that I'm committing?
You're on the right track, but looks like you're putting the values for shipment_version, testimonial_version and point_of_contact_version on the wrong JSONObject.
Judging by your desired JSON posted above, they should be added to pointofContact.
Your code should be doing something like this:
pointOfContact.put("shipment_version", "1");
pointOfContact.put("testimonial_version", "3");
pointOfContact.put("point_of_contact_version", "2");
data.put("username", "korea");
data.put("order_point_of_contact", pointofContact);
jsonObject.put("method", "version");
jsonObject.put("data", data);
The JSON should be nested correctly then.
Try the below given code:
JSONObject data = new JSONObject();
JSONObject pointofContact = new JSONObject();
JSONObject jsonObject = new JSONObject();
try {
pointofContact .put("shipment_version", "1");
pointofContact .put("testimonial_version", "3");
pointofContact .put("point_of_contact_version", "2");
data.put("username", "korea");
data .put("order_point_of_contact", pointofContact);
jsonObject.put("method", "version");
jsonObject.put("data", data);
} catch (JSONException e) {
e.printStackTrace();
}
Your json creation should be like this
JSONObject data = new JSONObject();
JSONObject pointofContact = new JSONObject();
JSONObject jsonObject = new JSONObject();
jsonObject .put("method", "version");
try {
data.put("username", "korea");
pointofContact.put("shipment_version", "1");
pointofContact.put("testimonial_version", "3");
pointofContact.put("point_of_contact_version", "2");
data.put("order_point_of_contact", pointofContact);
jsonObject .put("data",data);
} catch (JSONException e) {
e.printStackTrace();
}
Initial JSON
{
"data": [
{
"request": [
[
{
"name": "John""email": "John#gmail.com"
}
],
[
"name": "William""email": "William#gmail.com"
]
]
}
]
}
Corrected JSON as it was not passing through JSONLint
{
"data": [
{
"request": [
{
"name": "John",
"email": "John#gmail.com"
},
{
"name": "William",
"email": "William#gmail.com"
}
]
}
]
}
How to extract an array of JSON inside JSON array.I got error message as
json array cannot be converted into JSON Object.
Following code will help to parse your Json:
try {
JSONObject jsonData = new JSONObject(jsonObject);
JSONArray dataJsonArray = jsonData.getJSONArray("data");
JSONArray jsonRequest = dataJsonArray.getJSONObject(0)
.getJSONArray("request");
JSONArray mRequestChildJson = jsonRequest.getJSONArray(0);
JSONObject innerJson = mRequestChildJson.getJSONObject(0);
LogHandler.e("TAG",
"mRequestChildJson" + innerJson.toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
don't forgot to add check of has Key and size of array.
may be you're on right track but casting it in object
JSONArray JArray = jObject.getJSONArray("data");
try {
String str = result.toString();
System.out.println("prov-request -->"+str);
JSONObject json=new JSONObject(str);
JSONArray jsonarray = json.getJSONArray("data");
for(int i=0;i<jsonarray.length();i++){
JSONObject jsonnew=jsonarray.getJSONObject(i);
JSONArray jsonarrayROW = jsonnew.getJSONArray("request");
for(int j=0;j<jsonarrayROW.length();j++){
JSONObject jsonObject=jsonarrayROW.getJSONObject(j);
date.add(jsonObject.getString("name"));
from.add(jsonObject.getString("email"));
}
} catch (JSONException e) {
e.printStackTrace();
}