append data to existing JSON file - android

I'm using this code:
JSONObject jO = new JSONObject();
try {
jO.put("item1", true);
jO.put("item2", value2);
jO.put("item3", value3);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String json = null;
try {
json = jO.toString(4);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
File jsonFile = new File(nContext.getDir("json", 0), "dashboard.json");
//simple utility method to write the json file
Utils.writeToFile(jsonFile, json);
to have this result:
{
"item3": "12345",
"item2": "abcde",
"item1": true
}
What I want to achieve, on the next run of the same piece of code, is to end with something like:
{
"pass1": {
"item3": "12345",
"item2": "abcde",
"item1": true
},
"pass2": {
"item3": "67890",
"item2": "zxcvb",
"item1": true
}
}
Or maybe is it better to have this?
{
"pass1": [
{
"item3": "12345",
"item2": "abcde",
"item1": true
}
],
"pass2": [
{
"item3": "67890",
"item2": "zxcvb",
"item1": true
}
]
}
I know this implies a change in the code to include a "nested" object/array.
Which one is better, considering that I'll have to parse the JSON to build a ListView?
Any ideas?

I found the solution, thanks to the comments by other users and to a "retired" answer, not present here anymore. Maybe it was my fault not being clear.
public void addEntryToJsonFile(Context ctx, String id, String name, String size) {
// parse existing/init new JSON
File jsonFile = new File(ctx.getDir("my_data_dir", 0), "my_json_file.json");
String previousJson = null;
if (jsonFile.exists()) {
try {
previousJson = Utils.readFromFile(jsonFile);
} catch (IOException e) {
e.printStackTrace();
}
} else {
previousJson = "{}";
}
// create new "complex" object
JSONObject mO = null;
JSONObject jO = new JSONObject();
try {
mO = new JSONObject(previousJson);
jO.put("completed", true);
jO.put("name", name);
jO.put("size", size);
mO.put(id, jO); //thanks "retired" answer
} catch (JSONException e) {
e.printStackTrace();
}
// generate string from the object
String jsonString = null;
try {
jsonString = mO.toString(4);
} catch (JSONException e) {
e.printStackTrace();
}
// write back JSON file
Utils.writeToFile(jsonFile, jsonString);
}

Edited after dentex comment
Read your file
Parse the root Json object
If the root object not is already a complex object
Create a new root object
put your root object in it
put your second object in the root object
Write bnack your file
in pseudo code:
oldJson = ParseJsonFromFile()
newJson = {"item1": true, "item2": "abcde" ...}
JSONObject root;
if (oldJson.hasKey("pass1") {
root = oldJson
} else {
root = new JSONObject()
root.add("pass1", oldJson)
}
root.add("pass" + root.getSize() + 2, newJson)
WriteJsonToFile(root)

Related

POST JSON array with indices using retrofit

I'm using retrofit to POST a json array to server. Data is something like this:
{something:
{somethings:
[
{"param1":"value", "param2":value},
{"param1":"value", "param2":value}
]
}
}
however, my server forces me to MUST include the indices in the array like:
{something:
{somethings:
{
"0":{"param1":"value", "param2":value},
"1":{"param1":"value", "param2":value}
}
}
}
In other words cannot send parameters like this:
something[somethings][][param1]
something[somethings][][param2]
I must include indices:
something[somethings][0][param1]
something[somethings][0][param2]
How to do this using retrofit?
My interface looks like this:
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body Something something);
}
My classes look like following:
public class PostSomething {
private MapOfSomething something = new MapOfSomething();
public MapOfSomething getSomething() {
return portfolio;
}
public void setSomething(MapOfSomething something) {
this.something = something;
}
}
public class MapOfSomething {
private JSONObject somethings = new JSONObject();
public JSONObject getPortfolios() {
return somethings;
}
public void setSomethings(List<Something> somethingList) {
for (int i = 0; i<somethingList.size(); i++) {
try {
somethings.put(String.valueOf(i).toString(), somethingList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
and calling the method like:
PostSomethings something = new PostSomethings();
MapOfSomething map = new mapOfSomething();
map.setSomethings(listofSomething);
something.setSomethings(map);
apiService.postSomething(something);
One way to solve your problem is to put json directly into body , so your interface will look like this
interface ApiService {
#POST("endpoint")
public Callback<Something> postSomething (#Body JSONObject jsonObject);
}
Now you need to create the JSONObject , here is how I have created your desired JSONObject
JSONObject mainJson = new JSONObject();
JSONArray list = new JSONArray();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet1 = new JSONObject();
try {
singleElementSet1.put("1",singleElement1);
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElementSet2 = new JSONObject();
try {
singleElementSet2.put("2",singleElement2);
} catch (JSONException e) {
e.printStackTrace();
}
list.put(singleElementSet1);
list.put(singleElementSet2);
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("json",""+mainJson.toString());
I am assuming right now you are calling your service like this way
Call<Something> call = instanceOfYourAPIService.postSomething(anInstanceOfSomethingObject);
But now you have to replace this with the following
Call<Something> call = instanceOfYourAPIService.postSomething(mainJson); //mainJson is the JSONObject which is created earlier
Hope it helps
EDIT
JSONObject mainJson = new JSONObject();
JSONObject singleElement1 = new JSONObject();
try {
singleElement1.put("param1","value1");
singleElement1.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject singleElement2 = new JSONObject();
try {
singleElement2.put("param1","value1");
singleElement2.put("param2","value2");
} catch (JSONException e) {
e.printStackTrace();
}
ArrayList<JSONObject> jsonObjectArrayList = new ArrayList<JSONObject>();
//hope you can add item to this arraylist via some loop
jsonObjectArrayList.add(singleElement1);
jsonObjectArrayList.add(singleElement2);
JSONArray list = new JSONArray();
for(int i = 0;i<jsonObjectArrayList.size();i++){
JSONObject elementSet = new JSONObject();
try {
elementSet.put(String.valueOf(i).toString(),jsonObjectArrayList.get(i));
} catch (JSONException e) {
e.printStackTrace();
}
list.put(elementSet);
}
JSONObject subJson = new JSONObject();
try {
subJson.put("something",list);
mainJson.put("something",subJson);
} catch (JSONException e) {
e.printStackTrace();
}

How do i write nested JSON into HashMap<String,String>?

JSON:
{
"deviceId": "AAAAAAA1",
"cardInfo": {
"pan": "123456789012345",
"psn": "00",
"cvv": "123",
"panExpiryDate": "2017-12-12"
},
"productType": "CREDIT",
"requestor": 1234,
"aid": "A000000001234567",
"aidVersion": 1,
"panSource": null,
"deviceLanguage": "en"
}
Android Code:
protected String doInBackground(Void... params) {
Bundle bundle=getIntent().getExtras();
final String newdata=bundle.getString("newdata");
try {
js=new JSONObject(newdata);
di=js.getString("deviceId");
} catch (JSONException e) {
e.printStackTrace();
}
postDataParams = new HashMap<String, String>();
postDataParams.put("deviceId",deviceID);
postDataParams.put("cardInfo.pan",card);
postDataParams.put("cardInfo.psn",Psn);
postDataParams.put("cardInfo.cvv",cvv);
postDataParams.put("cardInfo.panExpiryDate",panExpiryDate);
postDataParams.put("productType",productType);
postDataParams.put("requestor",requestor);
postDataParams.put("aid",aid);
postDataParams.put("aidVersion",aidVersion);
postDataParams.put("panSource",panSource);
postDataParams.put("deviceLanguage",deviceLanguage);
response = service.postServerData(path,postDataParams);
try {
json = new JSONObject(response);
System.out.println("success " + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return response;
}
On writing this code am not getting any response from the url. Can you please help where i did the mistake.
Change this
postDataParams.put("cardInfo.pan",card);
postDataParams.put("cardInfo.psn",Psn);
postDataParams.put("cardInfo.cvv",cvv);
postDataParams.put("cardInfo.panExpiryDate",panExpiryDate);
to this
JSONObject cardInfoJson = new JSONObject();
cardInfoJson.put("pan", card);
cardInfoJson.put("psn", psn);
cardInfoJson.put("cvv", cvv);
cardInfoJson.put("panExpiryDate", panExpiryDate);
postDataParams.put("cardInfo", cardInfoJson);

Android - get data from json

I have a api call that returns this json object:
{
"elenco": [
"folder 1",
"folder 2",
"folder 3"
],
"codice": "123456789"
}
and this is my piece of code that get the result:
protected void onPostExecute(JSONObject result) {
// Close progress dialog
Dialog.dismiss();
JSONObject jobj = null;
String codice_utente = null;
JSONArray elenco_cartelle = null;
try {
jobj = new JSONObject(String.valueOf(result));
} catch (JSONException e) {
e.printStackTrace();
}
//Provo a recuperare i campi json
try {
codice_utente = jobj.getString("codice");
elenco_cartelle = jobj.getJSONArray("elenco");
} catch (JSONException e) {
e.printStackTrace();
}
//This should fetch the elenco array
for (int i = 0; i < elenco_cartelle.length(); i++) {
JSONObject childJSONObject = null;
try {
childJSONObject = elenco_cartelle.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
}
How can I fetch the elenco part? I do not have a key to use, so how can I add every row in an ArrayList?
I tried to use a for but I have no idea about how to get the rows
Use JSONArray.getString() http://developer.android.com/reference/org/json/JSONArray.html#getString(int)
for (int i = 0; i < elenco_cartelle.length(); i++) {
String content = null;
try {
content = elenco_cartelle.getString(i);
} catch (JSONException e) {
e.printStackTrace();
}
//Can't use getString here...
}
You now have your content on content

Android JSON object Parsing, unable to get status

{"Sam":{"status":"available","classkey":"dotnet"}}
How to parse this type of json?
try {
JSONObject jObj = new JSONObject(json);
if(jObj != null){
domtdl = jObj.getString(dom);
try {
JSONObject c = new JSONObject(domtdl);
if(c != null){
status = c.getString(TAG_STATUS);
System.out.println(status);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Is it correct?
I do not know how to get data from second JSON object.
Please help me.
For this specific json string {"Sam":{"status":"available","classkey":"dotnet"}}
you need to do
try {
JSONObject jObj = (new JSONObject(json)).getJSONObject("Sam");
String status = jObj.getString("status");
String classkey = jObj.getString("classkey");
} catch (JSONException e) {
e.printStackTrace();
}
try
{
JSONObject jb = new JSONObject(myjsonstring);
JSONObject job = jb.getJSONOBject("Sam");
String status = job.getString("status");
Log.i("Status is",status);
String classkey = job.getString("classkey");
Log.i("Class Key is",classkey);
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{ represents a json object node
{ // json object node
"Sam": { // json object SAM
"status": "available", json string
"classkey": "dotnet" json string
}
}
JSON Tutorial #
http://www.w3schools.com/json/
Your json can also look like below sometimes.
[ represents json array node
{
"employees": [
{
"firstName": "John",
"lastName": "Doe"
},
{
"firstName": "Anna",
"lastName": "Smith"
},
{
"firstName": "Peter",
"lastName": "Jones"
}
]
}
To parse the above
StringBuilder sb = new StringBuilder();
try {
JSONObject jb = new JSONObject(myjsonstring);
JSONArray jarr = jb.getJSONArray("employees");
for(int i=0;i<jarr.length();i++)
{
JSONObject job = jarr.getJSONObject(i);
String firstname = job.getString("firstName");
String lastname = job.getString("lastName");
sb.append(firstname);
Log.i("firstname",firstname);
sb.append("\n");
Log.i("lastname",lastname);
}
Toast.makeText(getApplicationContext(), sb, 10000).show();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

How to use Json Parsing?

Following is My Json File:-
"Restaurants":{
"8":{
"Res_name":"Purple Cafe and Wine Bar",
"foodtype":"American, Wine",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"9":{
"Res_name":"Quinn's",
"foodtype":"American, Pubs",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
"19":{
"Res_name":"Dahlia Lounge",
"foodtype":"American",
"city":"Seattle",
"state":"WA",
"latitude":"0",
"longitude":"0"
},
},
I am Using below code for json parsing:-
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurant = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
System.out.println("mRestaurant is:- " + mRestaurant);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The mRestaurant Value is below:-
{"487":{"state":"WA","Res_name":"SAM Taste","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"332":{"state":"WA","Res_name":"Luna Park Cafe","longitude":"0","latitude":"0","foodtype":"American","city":"Seattle"},"35":{"state":"WA","Res_name":"Restaurant Zoe","longitude":"0","latitude":"0","foodtype":"American, Bar","city":"Seattle"},"
but what is the next step for getting Res_Name, foodtype from above response.
Any Help would be appreciated.
The below code is next step for json parsing.
public void getdata() {
String res = mWebRequest.performGet(Constants.url+ "restaurants.php? action=searchRestaurant&lat=0&lon=0&foodtype="+ mEdttxtSearch.getText().toString() + "&state="+ mEdttxtSearch.getText().toString() + "&city="+ mEdttxtSearch.getText().toString()+ "&devType=Android");
System.out.println("res is:- " + res);
if (res != null) {
try {
JSONObject jsonObj = new JSONObject(res);
JSONObject mRestaurants = jsonObj.getJSONObject("Restaurants");
String mResult = jsonObj.getString("Result");
if (jsonObj.has("Restaurants")) {
Iterator<Object> keys = mRestaurants.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
JSONObject obj = new JSONObject();
obj = mRestaurants.getJSONObject(key);
mRes_Name.add(obj.getString("Res_name"));
mLatitude.add(obj.getString("latitude"));
mLongitude.add(obj.getString("longitude"));
mState.add(obj.getString("state"));
mCity.add(obj.getString("city"));
mFood_Type.add(obj.getString("foodtype"));
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use the get() method:
String mRestaurant = jsonObj.get("487").get("Res_name");
use gson for the same, as it supports direct conversion from json to java and java to json, please see following link:
Converting JSON to Java

Categories

Resources