How to Append Json object into existing json file in android - 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();
}

Related

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

Android: JSONException: Value null at VesselList of type org.json.JSONObject$1 cannot be converted to JSONArray

I'trying to Parsing JSOn object but sometime it runs properly sometime getting followoing error:
org.json.JSONException: Value null at VesselList of type
org.json.JSONObject$1 cannot be converted to JSONArray
public void getCompanyDeatails()
{
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/"+strSync_Time+"/Authentication_Token/"+str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet(strUrl_companyDeatls));
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
strResult = convertInputStreamToString(inputStream);
else
strResult = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
String jsonStr = strResult;
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null)
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString());
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
str_CompanyId = jobCompanyDetails.getString("Company_ID");
str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
if (dbhelper.isTitleExist(str_CompanyId)) {
//Upadte
dbhelper.updatedetails(str_CompanyId, str_CompanyName);
Log.e("Data updated in ", "Company Table !!");
} else {
//insert
dbhelper.insertCompany(str_CompanyId, str_CompanyName);
Log.e("Data inserted in ", "Company Table !!");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
this is my JSON String
{"Get_CompanyResult":{"CompanylList":[{"Company_ID":93,"Company_Name":"SeaChange"},{"Company_ID":97,"Company_Name":"VM 2"}],"Sync_Time":"2015-09-11 12:44:17.533"}}
Is this code is right?
Here:
JSONArray jarr = jsonObj.getJSONArray("CompanylList");
line causing issue because CompanylList JSONArray is inside Get_CompanyResult JSONObject instead of main which is jsonObj.
Get CompanylList JSONArray from companyList JSONObject:
JSONArray jarr = companyList.getJSONArray("CompanylList");
Change your code according to here :
public void getCompanyDeatails() {
String strUrl_companyDeatls = "http://103.24.4.60/CLASSNK1/MobileService.svc/Get_Company/Sync_Time/" + strSync_Time + "/Authentication_Token/" + str_Authentication_Token;
Log.e("strUrl_companyDeatls ", " = " + strUrl_companyDeatls);
InputStream inputStream = null;
String strResult = null;
try {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(new HttpGet("strUrl_companyDeatls"));
inputStream = httpResponse.getEntity().getContent();
// strResult = "{\\\"Get_CompanyResult\\\":{\\\"CompanylList\\\":[{\\\"Company_ID\\\":93,\\\"Company_Name\\\":\\\"SeaChange\\\"},{\\\"Company_ID\\\":97,\\\"Company_Name\\\":\\\"VM 2\\\"}],\\\"Sync_Time\\\":\\\"2015-09-11 12:44:17.533\\\"}}";
String jsonStr=null;
if (inputStream != null) {
strResult = convertInputStreamToString(inputStream);
jsonStr = strResult;
}
Log.e("jsonStr ", " = " + jsonStr);
if (jsonStr != null) {
JSONObject jsonObj = new JSONObject(jsonStr);
String jsonResult = jsonObj.toString().trim();
Log.e("jsonResult ", " = " + jsonResult);
JSONObject companyList = jsonObj.getJSONObject("Get_CompanyResult");
Log.e("companyList ", " = " + companyList.toString());
JSONArray jarr = companyList.getJSONArray("CompanylList");
Log.e("jarr ", " = " + jarr.toString()); // error was here. You need to use companyList json object because it contains company list.
for (int i = 0; i < jarr.length(); i++) {
JSONObject jobCompanyDetails = jarr.getJSONObject(i);
String str_CompanyId = jobCompanyDetails.getString("Company_ID");
String str_CompanyName = jobCompanyDetails.getString("Company_Name");
Log.e("str_CompanyId ", " = " + str_CompanyId);
Log.e("str_CompanyName ", " = " + str_CompanyName);
// if (dbhelper.isTitleExist(str_CompanyId)) {
// //Upadte
// dbhelper.updatedetails(str_CompanyId, str_CompanyName);
// Log.e("Data updated in ", "Company Table !!");
// } else {
//
// //insert
// dbhelper.insertCompany(str_CompanyId, str_CompanyName);
// Log.e("Data inserted in ", "Company Table !!");
// }
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
}
Note :
There is no need to use nested try and catch.
For 'strResult = "Did not work!";', always make sure that every
exception handled well (at checkpoint of jsonstr is null or not you
can not identify error occurred at parsing input stream can lead to
serious bugs).
HttpClient is deprecated so make sure you use latest version of any
third party library like Volley or Retrofit for network
operation and GSON for parsing response. It will minimize your
efforts.
Thanks.

How to check if two values are same or not from a JSONArray in android?

I am getting a Json response as below:
{
messages: [
{
id: "83",
payer_id: "5",
payee_id: "24",
payer_name: "vishal ",
payee_name: "ravi ",
payer_image: "upload/123.jpg",
payee_image: "upload/crop_110x110_1338731270_591178.jpg",
dispute_id: "43",
subject: "",
message_body: "dwedwde",
added_on: "2014-01-16 04:06:35",
sender_id: "5",
read: "1"
},
{
id: "716",
payer_id: "5",
payee_id: "6",
payer_name: "vishal ",
payee_name: "vishal ",
payer_image: "upload/123.jpg",
payee_image: "upload/yt.png",
dispute_id: "43",
subject: "",
message_body: "smthig",
added_on: "2014-05-27 02:26:04",
sender_id: "6",
read: "1"
}
],
status: "success"
}
I have coded as below for parsing.
ArrayList<HashMap<String, String>> msgList;
msgList = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(disputeURL, BackendAPIService.GET);
Log.print("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_MESSAGES)) {
System.out.println(":::::::::::::has::::::::::::");
msgArray = jsonObj.getJSONArray(Const.TAG_MESSAGES);
if (msgArray != null && msgArray.length() != 0) {
// looping through All Contacts
for (int i = 0; i < msgArray.length(); i++) {
System.out.println("::::::::::::ARRAY:::::::::::");
JSONObject c = msgArray.getJSONObject(i);
id = c.getString("id");
payee_id = c.getString("payee_id");
payer_id = c.getString("payer_id");
payer_name = c.getString("payer_name");
payee_name = c.getString("payee_name");
payer_image = c.getString("payer_image");
payee_image = c.getString("payee_image");
dispute_id = c.getString("dispute_id");
subject = c.getString("subject");
message_body = c.getString("message_body");
added_on = c.getString("added_on");
sender_id = c.getString("sender_id");
read = c.getString("read");
dispute_id = c.getString(Const.TAG_DIPUTE_ID);
System.out.println("::::::::::::sender Id::::::::::" + sender_id + ":::::::::::::::");
System.out.println("::::::::::::payee ID::::::::::" + payee_id + ":::::::::::::::");
HashMap<String, String> disputeMsgMap = new HashMap<String, String>();
disputeMsgMap.put(Const.TAG_ID, id);
disputeMsgMap.put(Const.TAG_PAYEE_ID, payee_id);
disputeMsgMap.put(Const.TAG_PAYER_ID, payer_id);
disputeMsgMap.put(Const.TAG_PAYER_NAME, payer_name);
disputeMsgMap.put(Const.TAG_PAYEE_NAME, payee_name);
disputeMsgMap.put(Const.TAG_PAYER_IMAGE, payer_image);
disputeMsgMap.put(Const.TAG_PAYEE_IMAGE, payee_image);
disputeMsgMap.put(Const.TAG_DIPUTE_ID, dispute_id);
disputeMsgMap.put(Const.TAG_SUBJECT, subject);
disputeMsgMap.put(Const.TAG_MESSAGE_BODY, message_body);
disputeMsgMap.put(Const.TAG_ADDED_ON, added_on);
disputeMsgMap.put(Const.TAG_READ, read);
disputeMsgMap.put(Const.TAG_SENDER_ID, sender_id);
msgList.add(disputeMsgMap);
}
}
So, I want to check that "sender_Id" of JSONObjects are different or not; I just want to check weather sender_id of any object is different or all are same.
You can iterate to all of your list of HashMap before you add it to the list and then check if the current sender_id is duplicated from the last list of hashmap's sender_id
example:
//TOP CODE ARE YOURS
if(msgList.size() != 0)
{
for(HashMap<String, String> hash : msgList) {
if(hash.get(sender_id) != null)
//YOU have a duplication of id
}
}
msgList.add(disputeMsgMap);

Get json array keys in android

{
"204": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/02\/0\/0\/A\/Content\/",
"timestamp": 1385909880,
"cover": ["17\/Pg017.png",
"18\/Pg018.png",
"1\/Pg001.png",
"2\/Pg002.png"],
"year": "2013",
"month": "12",
"day": "02",
"issue": "2013-12-02",
"id": "204"
},
"203": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/12\/01\/0\/0\/A\/Content\/",
"timestamp": 1385806902,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "12",
"day": "01",
"issue": "2013-12-01",
"id": "203"
},
"202": {
"host": "https:\/\/abc.com\/production-source\/ChangSha\/2013\/11\/30\/0\/0\/A\/Content\/",
"timestamp": 1385720451,
"cover": ["1\/Pg001.png",
"2\/Pg002.png",
"3\/Pg003.png",
"4\/Pg004.png"],
"year": "2013",
"month": "11",
"day": "30",
"issue": "2013-11-30",
"id": "202"
}
}
The above sample json array , how to get the 204, 203 and 202? Thanks
I tried:
JSONArray issueArray = new JSONArray(jsonContent);
for (int j = 0; j < issueArray.length(); j++) {
JSONObject issue = issueArray.getJSONObject(j);
String _pubKey = issue.getString(0);
}
above sample json array , how to get the 204, 203 and 202?
No, current String is JSONObject instead of JSONArray. you should get Iterator using JSONObject. keys () if inner JSONObject keys dynamic as:
JSONObject issueObj = new JSONObject(jsonContent);
Iterator iterator = issueObj.keys();
while(iterator.hasNext()){
String key = (String)iterator.next();
JSONObject issue = issueObj.getJSONObject(key);
// get id from issue
String _pubKey = issue.optString("id");
}
Answer given by Mr. K is also right but you can also use jsonObject names() method. please find the sample code
for(int i = 0; i<jsonobject.length(); i++){
Log.e(TAG, "Key = " + jsonobject.names().getString(i) + " value = " + jsonobject.get(jsonobject.names().getString(i)));
}
I hope dis will help you
User this method to iterate json dynamically
private void parseJson(JSONObject data) {
if (data != null) {
Iterator<String> it = data.keys();
while (it.hasNext()) {
String key = it.next();
try {
if (data.get(key) instanceof JSONArray) {
JSONArray arry = data.getJSONArray(key);
int size = arry.length();
for (int i = 0; i < size; i++) {
parseJson(arry.getJSONObject(i));
}
} else if (data.get(key) instanceof JSONObject) {
parseJson(data.getJSONObject(key));
} else {
System.out.println("" + key + " : " + data.optString(key));
}
} catch (Throwable e) {
System.out.println("" + key + " : " + data.optString(key));
e.printStackTrace();
}
}
}
}
You can also use names() as below to get the keys as JSONArray :
JSONArray jArray = jsonObject.names();
int len = jsonObject.length();
for (int i=0; i<len; i++) {
String keyName = (String)jArray.get(i);
JSONObject jValue = jsonObject.getJSONObject(keyName);
String _pubKey = jValue.optString("id");
//get the other values from jValue
}
Here you are trying to get JSONArray but in json response it is JSONObject.
Use following code.
JSONObject issueObject = new JSONObject(jsonContent);
String _pubKey = issueObject.getString(0);

Android create a Json String

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

Categories

Resources