Android create a Json String - android

I am trying to create a JSON String in the Android application.
JSONArray jArrayFacebookData = new JSONArray();
JSONObject jObjectType = new JSONObject();
// put elements into the object as a key-value pair
jObjectType.put("type", "facebook_login");
jArrayFacebookData.put(jObjectType);
// 2nd array for user information
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", id);
jObjectData.put("first_name", first_name);
jObjectData.put("last_name", last_name);
jObjectData.put("email", email);
jObjectData.put("username", username);
jObjectData.put("birthday", birthday);
jObjectData.put("gender", gender);
jObjectData.put("location", place);
jObjectData.put("display_photo", display_photo_url);
jArrayFacebookData.put(jObjectData);
Which creates a string like this
[
{
"type":"facebook_login"
},
{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206#gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
]
I want to create a JSON string something like this
[
"system":{
"type":"facebook_login"
},
"data":{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206#gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
]

JSONObject jArrayFacebookData = new JSONObject();
JSONObject jObjectType = new JSONObject();
// put elements into the object as a key-value pair
jObjectType.put("type", "facebook_login");
jArrayFacebookData.put("system", jObjectType);
// 2nd array for user information
JSONObject jObjectData = new JSONObject();
// Create Json Object using Facebook Data
jObjectData.put("facebook_user_id", id);
jObjectData.put("first_name", first_name);
jObjectData.put("last_name", last_name);
jObjectData.put("email", email);
jObjectData.put("username", username);
jObjectData.put("birthday", birthday);
jObjectData.put("gender", gender);
jObjectData.put("location", place);
jObjectData.put("display_photo", display_photo_url);
jArrayFacebookData.put("data", jObjectData);
this will give you jsonObject, but not array, i don't see any point in using JSONArray. JSONObject is better in this case. you will see following output as String
{
"system":{
"type":"facebook_login"
},
"data":{
"birthday":"06\/22\/1986",
"first_name":"Harsha",
"username":"harshamv",
"location":"Bangalore, India",
"email":"hmv2206#gmail.com",
"last_name":"Mv",
"gender":"male",
"facebook_user_id":"1423671254",
"display_photo":"http:\/\/graph.facebook.com\/1423671254\/picture?type=large"
}
}

Create JSON objects for the jArrayFacebookData (not JSONArray as you have taken) and put jObjectType and jObjectData inside it.
Check this JSONObject put object method.
Update:
Your JSON is having error:
Valid JSON is:
{
"system": {
"type": "facebook_login"
},
"data": {
"birthday": "06/22/1986",
"first_name": "Harsha",
"username": "harshamv",
"location": "Bangalore, India",
"email": "hmv2206#gmail.com",
"last_name": "Mv",
"gender": "male",
"facebook_user_id": "1423671254",
"display_photo": "http://graph.facebook.com/1423671254/picture?type=large"
}
}
Final Solution:
try
{
JSONObject jArrayFacebookData = new JSONObject();
JSONObject jObjectType = new JSONObject();
jObjectType.put("type", "facebook_login");
JSONObject jObjectData = new JSONObject();
jObjectData.put("facebook_user_id", "2323");
jObjectData.put("first_name", "2323");
jObjectData.put("last_name", "2323");
//put other data here
jArrayFacebookData.put("system", jObjectType);
jArrayFacebookData.put("data",jObjectData);
System.out.println("==========> Final output => "+jArrayFacebookData.toString());
}
catch(Exception e)
{
}

how i post json string.
for(int i=0; i<iArr.size(); i++){
if(i==0){
st = "{\"userId\":" + iArr.get(i) + "}";
str += st;
}else if(i>0 && i<iArr.size()-1){
st = ",{\"userId\":" + iArr.get(i) + "}";
str+=st;
}else if(i==iArr.size()){
st = ",{\"userId\":" + iArr.get(i) + "}]}";
str+=st;
}
}
String myPost = "{\"project\":{\"Name\":"+ "\""+ title + "\""
+ ",\"Description\":" + "\""+ desc + "\""
+ ",\"createdBy\":" + usrid + ""
+ ",\"startDate\":" + "\""+ startdate + "\""
+ ",\"dueDate\":" + "\""+ duedate + "\""
+ ",\"projectLeadId\":" + leadPosition + ""
+ ",\"QAId\":" + QAssurencePosition + ""
+ ",\"TotalHour\":" +"\""+ edtHour + "\""+ "},\"members\":[";
myPost += str;
myPost +="]}";
RequestPackage myPackage = new RequestPackage();
myPackage.setUri(getaddProject);
myPackage.setMethod("POST");
myPackage.setParam("My Post",myPost+"");
new MyTask().execute(myPackage);
Toast.makeText(CreateProject.this,"Testing String: " + myPost,Toast.LENGTH_LONG ).show();
Log.d("My Post :",myPost);
}

Related

Get data from JSON object and array

Searching for solution of that. Sample of Java code:
public void loadPositions(JSONObject result){
try {
JSONObject jObject = result.getJSONObject("points");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.v("list key", key);
if(jObject.get(key) instanceof JSONObject) {
JSONObject innerJObject = jObject.getJSONObject(key);
String lat = innerJObject.getString("lat");
String lon = innerJObject.getString("lon");
Log.i("details", "lat = " + lat + ", " + "lon = " + lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
JSON data:
{
"points":{
"C50D15525":[
{
"lat":"51.643257329609156",
"lon":"17.798963651975885"
},
{
"lat":"51.643257329609156",
"lon":"17.798963651975885"
}
],
"BFFCDE4AF":[
{
"lat":"51.6434779",
"lon":"17.7993028"
},
{
"lat":"51.6434779",
"lon":"17.7993028"
},
{
"lat":"51.6434779",
"lon":"17.7993028"
}
]
}
}
Code above give me only list key, but I want LAT & LON from many points like "BFFCDE4AF" and "C50D15525". I've tried in many ways... JSON data is valid.
You can achive it through this
For example
points.C50D15525["lat"]
but you need to extract json through apply any looping and associative concept.
Inside the "points" object your JSON has an Array object, which you need to get with the getJSONArray() method. Loop through the JSONArray and get the "lat" and "lon" objects.
public void loadPositions(JSONObject result){
try {
JSONObject jObject = result.getJSONObject("points");
Iterator<String> keys = jObject.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.v("list key", key);
JSONArray jArray = jObject.getJSONArray(key);
for (int i=0; i < jArray.length(); i++){
JSONObject obj = jArray.getJSONObject(i);
String lat = obj.optString("lat", "NA"));
String lon = obj.optString("lon", "NA"));
Log.i("details","key = " + key + " coor count = " + i + " lat = " + lat + ", " + "lon = " + lon);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
Since I have not tested this, please let me know if you have any issues.

How to Append Json object into existing json file in android

My json file contains,
{
"appointments": [
{
"appointmentId": "app_001",
"appointmentTitle": "Appointment Title1",
"appointmentDate": "2017-11-25",
"appointmentTime": "10:30",
"appointmentStatus": "active",
"appointmentType": "meeting",
"reminder": {
"type": "notification",
"time": "10:15",
"status": "off"
},
"appointmentDescription": "blablablablabla1"
},
{
"appointmentId": "app_002",
"appointmentTitle": "AppointmentTitle2",
"appointmentDate": "2017-11-26",
"appointmentTime": "09:00",
"appointmentStatus": "done",
"appointmentType": "exam",
"reminder": {
"type": "alarm",
"time": "08:45",
"status": "on"
},
"appointmentDescription": "blablablablabla2"
}
]
}
I need to put another jsonobject into array, Out put should be like,
{
"appointments": [
{
"appointmentId": "app_001",
"appointmentTitle": "Appointment Title1",
"appointmentDate": "2017-11-25",
"appointmentTime": "10:30",
"appointmentStatus": "active",
"appointmentType": "meeting",
"reminder": {
"type": "notification",
"time": "10:15",
"status": "off"
},
"appointmentDescription": "blablablablabla1"
},
{
"appointmentId": "app_002",
"appointmentTitle": "AppointmentTitle2",
"appointmentDate": "2017-11-26",
"appointmentTime": "09:00",
"appointmentStatus": "done",
"appointmentType": "exam",
"reminder": {
"type": "alarm",
"time": "08:45",
"status": "on"
},
"appointmentDescription": "blablablablabla2"
},
{
"appointmentId": "app_003",
"appointmentTitle": "AppointmentTitle3",
"appointmentDate": "2017-11-26",
"appointmentTime": "09:00",
"appointmentStatus": "done",
"appointmentType": "exam",
"reminder": {
"type": "alarm",
"time": "08:45",
"status": "on"
},
"appointmentDescription": "blablablablabla3"
}
]
}
I used following code segment perform my requirement.
File fileJson = new File(getApplicationContext().getExternalFilesDir("/app"), "app.json");
String strFileJson = getStringFromFile(fileJson.toString());
JSONObject jsonObj = new JSONObject(strFileJson);
jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");
JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");
writeJsonFile(fileJson, jsonObj.toString());
writeJsonFile, getStringFromFile, convertStreamToString functions are,
public static String getStringFromFile(String filePath) throws Exception {
File fl = new File(filePath);
FileInputStream fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
//Make sure you close all streams.
fin.close();
return ret;
}
public static String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
public static void writeJsonFile(File file, String json) {
BufferedWriter bufferedWriter = null;
try {
if (!file.exists()) {
Log.e("App","file not exist");
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(json);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bufferedWriter != null) {
bufferedWriter.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
but the output I am getting is,
{
"appointments": [
{
"appointmentId": "app_001",
"appointmentTitle": "Appointment Title1",
"appointmentDate": "2017-11-25",
"appointmentTime": "10:30",
"appointmentStatus": "active",
"appointmentType": "meeting",
"reminder": {
"type": "notification",
"time": "10:15",
"status": "off"
},
"appointmentDescription": "blablablablabla1"
},
{
"appointmentId": "app_002",
"appointmentTitle": "AppointmentTitle2",
"appointmentDate": "2017-11-26",
"appointmentTime": "09:00",
"appointmentStatus": "done",
"appointmentType": "exam",
"reminder": {
"type": "alarm",
"time": "08:45",
"status": "on"
},
"appointmentDescription": "blablablablabla2"
}
],
"appointmentId": "app_002",
"appointmentTitle": "Appointment Title2",
"appointmentDate": "2017-11-21",
"appointmentTime": "01:30",
"appointmentStatus": "active",
"appointmentType": "meeting",
"reminder": {
"type": "note",
"time": "12:30",
"status": "off"
},
"appointmentDescription": "blablablablabla2"
}
Please help me to get required format of json as output. Thanks in advance
Hope this would do what you want, Replace your
JSONObject jsonObj = new JSONObject(strFileJson);
jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");
JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");
with this,
JSONObject PreviousJsonObj = new JSONObject(strFileJson);
JSONArray array = PreviousJsonObj.getJSONArray("appointments");
JSONObject jsonObj= new JSONObject();
jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");
JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");
array.put(jsonObj);
JSONObject currentJsonObject = new JSONObject();
currentJsonObject.put("appointments",array);
You are almost on the right track. you just have to add the JSONObject inside your JSONArray. Try this
JSONObject OldJsonObj = new JSONObject(strFileJson);
JSONArray array = OldJsonObj.getJSONArray("appointments");
JSONObject jsonObj= new JSONObject();
jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");
JSONObject reminder = new JSONObject();
reminder.put("type", "note");
reminder.put("time", "12:30");
reminder.put("status", "off");
jsonObj.put("reminder", reminder);
jsonObj.put("appointmentDescription", "blablablablabla2");
array.put(jsonObj); // put the data in array
JSONObject newJsonObject = new JSONObject(array.toString());
writeJsonFile(fileJson, newJsonObject .toString());
You can use FileWriter to write in text files. Use below code:
try{
FileWriter fileWriter = new FileWriter(Environment.getExternalStorageDirectory().getPath() + "/Android/data/com.StampWallet/" + "SBLog.txt", true);
fileWriter.write("Hello");
fileWrite.close();
}catch(IOException e){
}
know more about it visit here
You can use Gson to convert object in string or vice-versa.
You will have to add the JSONObject inside your JSONArray appointments, try this
JSONObject jsonObject=new JSONObject(strFileJson);
JSONObject jsonObj=new JSONObject();
JSONObject jObj=new JSONObject();
try {
jsonObj.put("appointmentId", "app_002");
jsonObj.put("appointmentTitle", "Appointment Title2");
jsonObj.put("appointmentDate", "2017-11-21");
jsonObj.put("appointmentTime", "01:30");
jsonObj.put("appointmentStatus", "active");
jsonObj.put("appointmentType", "meeting");
jObj.put("type", "note");
jObj.put("time", "12:30");
jObj.put("status", "off");
jsonObj.put("reminder",jObj);
JSONArray jsonArray=jsonObject.getJSONArray("appointments");
jsonArray.put(jsonObj);
} catch (JSONException e) {
e.printStackTrace();
}
You need to get all the json objects from the json file first, parse it, then add new json array to it, finally save it back to the file.
This is the method that appends new string to existing Json File and make it in proper format.
public void runCheck() throws Exception {
String fileName= "E:\\stores.json"; //my existing json file
//this methods first gets the existing json string from our file.
BufferedReader br = new BufferedReader(new FileReader(fileName));
StringBuilder sb = new StringBuilder();
line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
br.close();
String mk="suraj"; //variable to be inserted in my new json
//this methods removes the trailing bracket so that i can append my new json
String str =sb.toString();
String sourceWord="}";
StringBuilder strb=new StringBuilder(str);
int index=strb.lastIndexOf(sourceWord);
strb.replace(index,sourceWord.length()+index,"");
System.out.println(strb.toString());
FileWriter fws = new FileWriter(fileName,false);
fws.write(strb.toString());//appends the string to the file
fws.close();
//now the method to insert new json
FileWriter fw = new FileWriter(fileName,true); //the true will append the new data
String json = " , \n"
+ "\""
+ mk
+ "\": \n"
+ "{ \n"
+ " \"prod\": \n"
+ "{ \n"
+ " \"MAGENTO_ADMIN_PASSWORD\": \""
+ mk
+ "\", \n"
+ " \"MAGENTO_ADMIN_USERNAME\" : \""
+ mk
+ "\", \n"
+ " \"MAGENTO_BACKEND_NAME\" : \""
+ mk
+ "\", \n"
+ " \"MAGENTO_BASE_URL\" : \""
+ mk
+ "\" \n"
+ " }, \n"
+ " \"uat\": \n"
+ " { \n"
+ " \"MAGENTO_ADMIN_PASSWORD\": \""
+ mk
+ "\", \n"
+ " \"MAGENTO_ADMIN_USERNAME\" : \""
+ mk
+ "\", \n"
+ " \"MAGENTO_BACKEND_NAME\" : \""
+ mk
+ "\", \n"
+ " \"MAGENTO_BASE_URL\" : \""
+mk
+ "\" \n"
+ " }, \n"
+ " \"stag\": \n"
+ " { \n"
+ " \"MAGENTO_ADMIN_PASSWORD\": \""
+ mk
+ "\", \n"
+ " \"MAGENTO_ADMIN_USERNAME\" : \""
+ mk
+ "\", \n"
+ " \"MAGENTO_BACKEND_NAME\" : \""
+ mk
+ "\",\n"
+ " \"MAGENTO_BASE_URL\" : \""
+ mk
+ "\" \n"
+ " } \n"
+ "} \n";
fw.write(json);//appends the string to the file
fw.write( "} \n"); //append my closing bracket, You can modify as per your convinience.
fw.close();
}

How i can access this Json from my AsyncTask?

I'm trying to retrieve data from Json Like below :
{
comments: [
{
id: 78,
comment_user_id: 81,
comment_is_approve: 1,
comment_ads_id: 373,
comment_text: "commmmmmeeeent here ",
created_at: "2017-03-19 08:32:17",
updated_at: "2017-03-19 08:32:17",
user: {
id: 81,
first_name: "name",
last_name: "",
age: "",
email: "l#mail.com",
telephone: "234234234",
}
}
]
}
and here is my asyncTask() :
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url + 373, "GET", params);
// Check your log cat for JSON reponse
//Log.d("All Comments: ", json.toString());
try {
JSONArray comments = json.getJSONArray("comments");
// looping through All Comments
for (int i = 0; i < comments.length(); i++) {
JSONObject c = comments.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("id");
String commentText = c.getString("comment_text");
String name = "";
String phone = "";
Log.i(TAG, "doInBackground Items: " + id + " , "+ commentText);
//Loop through All user details
JSONArray arrUser = c.getJSONArray("user");
int l = 0;
JSONObject user = arrUser.getJSONObject(l++);
name = user.getString("first_name");
phone = user.getString("telephone");
// creating new HashMap
Log.i(TAG, "doInBackground Items: " + name +", " + commentText + ", " + phone);
// adding HashList to ArrayList
mapItems = new HashMap<>();
// adding each child node to HashMap key => value
mapItems.put("id", id);
mapItems.put("first_name", name);
mapItems.put("comment_text", commentText);
mapItems.put("telephone", phone);
contactList.add(mapItems);
I can get commentText and id , but i can't get any data from user array ?
should i add parantethes to users or how i can achieve that ?
Here user is not an array..it is a JsonObject
try this:
JSONObject User = c.getJSONObject("user");
String id = User.getString("id");
String first_name = User.getString("first_name");
or modify your json response to return an array instead.
Also your JSON response is invalid.
this is the valid JSON response:
{
"comments": [{
"id": 78,
"comment_user_id": 81,
"comment_is_approve": 1,
"comment_ads_id": 373,
"comment_text": "commmmmmeeeent here ",
"created_at": "2017-03-19 08:32:17",
"updated_at": "2017-03-19 08:32:17",
"user": {
"id": 81,
"first_name": "name",
"last_name": "",
"age": "",
"email": "l#mail.com",
"telephone": "234234234" //remove comma here
}
}]
}
you can check valid JSON from HERE
you have to apply nested structure like this
JSONArray arrUser1 = c.getJSONArray("user");
for (int j = 0; j < arrUser1.length(); j++) {
JSONObject c1 = arrUser1.getJSONObject(j);
name = c1.getString("first_name");
phone = c1.getString("telephone");
mapItems = new HashMap<>();
mapItems.put("id", id);
mapItems.put("first_name", name);
mapItems.put("comment_text", commentText);
mapItems.put("telephone", phone);
contactList.add(mapItems);
}
User is a JSONObject in this case. I am not sure why you have used a JSONArray.
This should be enough.
JSONObject user = c.getJSONObject("user");
name = user.getString("first_name");
phone = user.getString("telephone");

How i can retrieve this array of images from json?

I have his json and i need to retrieve array of images from images Variable..
this my json :
{
id: 215,
title: " this is title",
image: "1464958558.jpg",
description: "description",
images: "["1464958558.jpg","1464958559.jpg","1464958561.jpg","1464958563.jpg","1464958564.jpg","1464958568.jpg","1464958569.jpg","1464958570.jpg","1464958573.jpg","1464958574.jpg"]",
user_name: "user name",
telephone: "0123456789"
}
i want to retrieve this images array and display it in grid view... and i can't find any response in logcat
my doInBackGround()
#Override
protected Integer doInBackground(String... arg0) {
// Building Parameters
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
ID = mCursor.getString(ArticleLoader.Query._ID);
String jsonStr = sh.makeServiceCall(String.valueOf(Config.BASE_URL));
//jsonStr = sh.makeServiceCall(url + 373); //or url + ID
Log.i(TAG, "doInBackground Image: " + String.valueOf(Config.BASE_URL));
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
GridItem item;
item = new GridItem();
Log.i(TAG, "parseResult: " + jsonObj);
for (int i = 0; i < jsonObj.length(); i++) {
// if (response != null) {
String images = jsonObj.getString("images");
item.setImage(IMAGE_LINK + images);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + images);
mGridData.add(item);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
return null;
}
dose i retrieve data correctly ?
Is images json object string or json array? In your code is string.
If WebService changes are possible, request to given you a json array of images, this is best practice.
If not possible you must parse json image object with regex.
No your doing wrong just try below code
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray arrayObj = jsonObj.getJSONArray("images");
for(int i=0;i<arrayObj.length();i++)
{
String item = arrayObj.getString(i);
// now you use item string where you want
}
} catch (JSONException e) {
e.printStackTrace();
}
images should be a JSONArray, and hence you can do that to parse it (inside your for loop!):
JSONArray imagesJSON = jsonObj.getJSONArray("images");
for(int k = 0 ; k<imagesJSON.length() ; k++){
String image = imagesJSON.getString(k);
item.setImage(IMAGE_LINK + image);//IMAGE_LINK +
Log.i(TAG, "parseResult: " + IMAGE_LINK + " " + image);
mGridData.add(item);
}

How do you pass results from a JSON array into into a multidimensional array?

I am a little new to android/java. I am trying to pass JSON values into a list and then into a multidimensional array. I am not having much success.
2 questions,
1) How would I load all of the variables in a json array into children[][]?
2) How do you view children[][] in Log.i
Herei s my code:
List<String> cList = new ArrayList<String>();
String customer_name, customer_title, customer_postal_code, customer_city, customer_state, customer_street_address;
ArrayList<String> cTitle, cClubName, cPostalCode, cCity, cState, cStreet = new ArrayList<String>();
public String[][] children = null;
//... onCreate method, HTTP Connection, StringBuilder, etc. These work fine...
// Pass data into array
try{
JSONArray jArray = new JSONArray(result);
JSONObject jData=null;
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
cList.add(customer_name);
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
cList.add(customer_title);
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
cList.add(customer_street_address);
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
cList.add(customer_city);
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
cList.add(customer_state);
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
cList.add(customer_postal_code);
for(int ic = 0; ic < cList.size(); ic++) {
Log.i("jData ", "length " + jData.length());
children[i][ic] = (String) cList.get(ic);
}
Log.i("Child Array", "Children array LOG " + children);
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No customers Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
If I understood your code correctly you don't need cList.
Something like that should do the work
String[][] children = new String[jArray.length()][6];
for(int i=0;i<jArray.length();i++){
jData = jArray.getJSONObject(i);
customer_name=jData.getString("customer_name");
Log.i("JSON ", "customer_name LOG " + customer_name);
children[i][0] = customer_name;
customer_title=jData.getString("event_title");
Log.i("JSON ", "customer_title LOG " + customer_title);
children[i][1] = event_title;
customer_street_address=jData.getString("customer_street_address");
Log.i("JSON ", "customer_Id LOG " + customer_street_address);
children[i][2] = customer_street_address;
customer_city=jData.getString("customer_city");
Log.i("JSON ", "customer_city LOG " + customer_city);
children[i][3] = customer_city;
customer_state=jData.getString("customer_state");
Log.i("JSON ", "customer_state LOG " + customer_state);
children[i][4] = customer_state;
customer_postal_code=jData.getString("customer_postal_code");
Log.i("JSON ", "customer_postal_code LOG " + customer_postal_code);
children[i][5] = customer_postal_code;
}
Make sure your JSON data is well-formed to avoid exceptions.
To view children[][] you can just iterate twice on your multidimentional array and do Log.i("MyTag", "Value: " + children[i][j]);
String[][] data = new String[jsonArray.length][];
for(int i = 0; i<jsonArray.length; i++){
data[i] = ((ArrayList)jsonArray).get(i).toArray(new String[((ArrayList)jsonArray).get(i).size])
}
for printing in log
Log.d("array", data);

Categories

Resources