I am working on an android application using a json file in order to store data used by the application.
I have a Json file in the asset folder, including one object "plants".
In the Dashboard.java file, I would like to add an object to the json file.
I tried this by using the put() function, but I doesnt seem to write in the actual file.
Dashboard.java :
String name = intent.getStringExtra(AddAPlant.EXTRA_TEXT1);
String description = intent.getStringExtra(AddAPlant.EXTRA_TEXT2);
String url = intent.getStringExtra(AddAPlant.EXTRA_TEXT3);
JSONObject jsonObj= new JSONObject();
try {
jsonObj.put("name", name);
jsonObj.put("description", description);
jsonObj.put("cameralink", url);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
plantArray = new JSONArray();
plantArray.put(jsonObj);
Json file located in asset folder :
{
"plants": [
{
"name": "Pepper",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png"
},
{
"name": "Tomatoe",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png"
},
{
"name": "Small Tomato",
"decription": "It needs a lot of water",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png"
}
]
}
Desired output :
{
"plants": [
{
"name": "Pepper",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam1-snapshots/gallery-images/latest.png"
},
{
"name": "Tomatoe",
"decription": "This is a big plant",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam2-snapshots/gallery-images/latest.png"
},
{
"name": "Small Tomato",
"decription": "It needs a lot of water",
"CameraLink": "https://messir.uni.lu/bicslab/blab-cam3-snapshots/gallery-images/latest.png"
},
{
"name": name,
"decription": description,
"CameraLink": url
]
}
i do not think it is possible to write to /assets at run time check this answer
try using app specific files docs
To make changes to JSON. Read from file (String data) and initialize a JSONobject.
JSONObject obj = new JSONObject("string from your file")
JSONObject jsonObject = new JSONObject("data from file");
JSONArray jsonArray = jsonObject.getJSONArray("plants");
JSONObject jsonObj = new JSONObject();
jsonObj.put("name", name);
jsonObj.put("description", description);
jsonObj.put("cameralink", url);
jsonArray = jsonArray.put(jsonObj);
jsonObject = jsonObject.put("plants", jsonArray);
//convert json object to string
String data = jsonObject.toString();
FileOutputStream fout = context.openFileOutput(filename, Context.MODE_PRIVATE);
fout.write(data.getBytes());
Related
I am unable to create a json object for nested json.
I can create json objects for basic json.
I am unable to add further fields.
final JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
} catch (JSONException e) {
e.printStackTrace();
}
Here is my json:
{
"name": "string",
"description": "string",
"candidates": [
"string"
],
"ballotVisibility": "string",
"voterListVisibility": true,
"startingDate": "2019-07-05T20:09:23.311Z",
"endingDate": "2019-07-05T20:09:23.311Z",
"isInvite": true,
"isRealTime": true,
"votingAlgo": "string",
"noVacancies": 0,
"ballot": [
{
"voteBallot": "string",
"voterEmail": "string"
}
]
}
You just need to create a new JSONObject then append it to the parent object with its new name. An example is shown below appending the ballot:
JSONObject jsonObject = new JSONObject();
JSONObject ballot = new JSONObject();
ballot.put("voteBallot","string");
ballot.put("voterEmail","string");
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("ballot", ballot); //Append the other JSONObject to the parent one
System.out.println(jsonObject.toString());
Output(with some formatting):
{
"ballot":
{
"voteBallot":"string",
"voterEmail":"string"
},
"name":"new name",
"description":"new election"
}
You can also use JSONArray instead and append it in the same manner.
Try this:
final JSONObject jsonObject = new JSONObject();
Map<String, String> map = new HashMap<>();
map.put("voteBallot", "string");
map.put("voterEmail", "string");
try {
jsonObject.put("name", "new name");
jsonObject.put("description", "new election");
jsonObject.put("candidates", new String[] {"new String"});
jsonObject.put("ballotVisibility", "string");
jsonObject.put("voterListVisibility", true);
jsonObject.put("startingDate", LocalDateTime.now().atZone(ZoneOffset.UTC));
jsonObject.put("ballot", new Map[]{map});
System.out.println("jsonObject = " + jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
it's not all the fields but it's all the different types hope it helps.
Output:
{
"ballot":[
{
"voteBallot":"string",
"voterEmail":"string"
}
],
"candidates":[
"new String"
],
"ballotVisibility":"string",
"name":"new name",
"voterListVisibility":true,
"description":"new election",
"startingDate":"2019-07-05T22:34:58.750Z"
}
I have been battling with response from server using retrofit.
I have this json response from server
{
"success": true,
"message": "Your Requests",
"data": {
"requests": [
{
"_id": "5d163a5ed2399f8be6d8d867",
"created": "2019-06-28T16:03:42.463Z",
"pickupCoordinates": [
8.0099,
6.0909
],
"destinationCoordinates": [
9.088788,
3.099403
],
"customerName": "Seun Akinbode",
"pickupAddress": "Lekki",
"destinationAddress": "Ajah",
"accessCode": "3334",
"busPlate": "DD222RR",
"flaName": "Simi",
"flaEmail": "awele#kobo360.com",
"__v": 0
} ]
}
I use below class to parse the json but unfortunately, it couldn't extract the array requests into jsonArray
public ArrayList<RequestModel> getData(String response)
{
Log.d("responseData :", response);
ArrayList<RequestModel> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("data");
Log.d("The main Array :", array.toString());
RequestModel data;
for(int i = 0;i<array.length();i++)
{
data = new RequestModel();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requests");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
data.setAccessCode(reqObj.getString("accessCode"));
Log.d("Accessecode :", reqObj.getString("accessCode"));
data.setCustomerName(reqObj.getString("customerName"));
Log.d("customerName :", reqObj.getString("customerName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
Logcat is printing the JSONObject but it says at ... data of type org.json.JSONObject cannot be converted to JSONArray
You are trying to extract an array from the data field, while the response contains an object. Perhaps you meant to get the object data, then the array requests from within it.
This could be the problem:
JSONArray array = mainObj.getJSONArray("data");
data is an object as seen in the response, not an array.
I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
{
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890"
},
{
"id": 2,
ETC...
I need to process another JSON file but it has a different structure:
{
"contacts": {
"1": {
"id": 1,
"name": "name1",
"email": "email1",
"phone": "1234567890",
"level1": {
"level2": {
"level3": 3,
}
},
"last_updated": 20180712
},
"2": {
ETC...
How do I process this second JSON file by adjusting the below code?
if (jsonSource != null) {
try {
JSONObject jsonObject = new JSONObject(jsonSource);
JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");
for (int i = 0; i < jsonArrayData.length(); i++) {
JSONObject contacts = jsonArrayData.getJSONObject(i);
String id = contacts.getString("id");
String name = contacts.getString("name");
String email = contacts.getString("email");
String phone = contacts.getString("phone");
HashMap<String, String> values = new HashMap<>();
values.put("id", id);
values.put("name", name);
values.put("email, email);
values.put("phone, phone);
contactList.add(values);
}
} catch (final JSONException e) {
Log.e(TAG, "JSON parsing error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
} else {
Log.e(TAG, "Unable to retrieve JSON file from URL");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
}
});
}
return null;
Any help is much appreciated!
It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
{...},
{...},
{...}
]
"contacts": {
"1": {...},
"2": {...},
"3": {...}
}
So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
JSONObject contactsJson = jsonObject.getJSONObject("contacts");
for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
String key = it.next();
JSONObject contactJson = contactsJson.getJSONObject(key);
// your code to process contact item
}
} else {
// Your code to process every contact item
}
I just tried to get values that are stored in my JSON file and save it into sqlite database:
This is my JSON file:
{
"list": {
"meta": {
"count": 132,
"start": 0,
"type": "resource-list"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 3.6720000000000002,
"type": "currency",
"symbol": "AED=X"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 65.075000000000003,
"type": "currency",
"symbol": "AFN=X"
}
}
},
{
.............
}
............
I have tried like this but getting exception :
JSONObject mainObj = null;
try {
mainObj = new JSONObject(JSON);
JSONObject getSth = mainObj.getJSONObject("list");
if(mainObj != null){
JSONArray list = getSth.getJSONArray("resources");
if(list != null){
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
if(elem != null){
JSONObject prods = elem.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),""+e.toString(),Toast.LENGTH_LONG).show();
}
I was getting exception : no values in fields...
And pls give some suggestions that storing these values in Database table(matrotable) of(row fields) name, prize, symbol and type, I may try by making String Array and retrieving and storing the values for sqlite, is there any other easy options...
thanks
your fields objects are inside resource object so do
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
if(elem != null){
JSONObject prods = elem.getJSONObject("resource")
.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
"resources": [ // resources list
{ // object i
"resource": { // fields are inside "resource" object
"classname": "Quote",
"fields": {
"date": "2017-03-16",
"price": 3.6720000000000002,
"type": "currency",
"symbol": "AED=X"
}
}
}
You are missing the resource JOSNObject parsing...
for(int i = 0; i < list.length();i++){
JSONObject elem = list.getJSONObject(i);
JSONObject resource = elem.getJSONObject("resource");
if(resource != null){
JSONObject prods = resource.getJSONObject("fields");
Object level = prods.get("type");
Toast.makeText(getApplicationContext(),""+level.toString(),Toast.LENGTH_LONG).show();
}
}
I recommend to you to use the simplest and easiest way to parse a json response to avoid this kind of issues:
1- generate your model classes by using this tool: http://www.jsonschema2pojo.org/ download and add the generated classes to your model package.
2- add this dependency to your gradle file:
compile 'com.google.code.gson:gson:2.4'
3- Call this method to parse your response:
Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson(json, ResponseModel.class);
[
{
"description": "My home",
"name": "Sweet Home",
"point": {
"lat": 22.890976,
"long": 90.459097
},
"type": 1,
"cid": "5319197376176516414"
}
This is my json file for parsing information. Here is my code for parsing name and lng.
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.map)));
StringBuilder jsonBuilder = new StringBuilder();
try {
for (String line = null; (line = jsonReader.readLine()) != null;) {
jsonBuilder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(jsonBuilder.toString());
JSONArray jsonArray = new JSONArray(tokener);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String title = jsonObject.getString("name");
String lhg = jsonObject.getJSONObject("point").getString("lng");
} catch (FileNotFoundException e) {
Log.e("jsonFile", "file not found");
} catch (IOException e) {
Log.e("jsonFile", "ioerror");
} catch (JSONException e) {
Log.e("jsonFile", "error while parsing json");
}
}
}
It show's me an exception error while parsing json. How do i solve that? What was my problem?
Because "Point" in your JSON object never contains a property called "lng"
String lhg = jsonObject.getJSONObject("point").getString("lng")
it does contain one named "long"
"point": {
"lat": 22.890976,
"long": 90.459097
},
So the code to fetch the longitude should look like this:
String lhg = jsonObject.getJSONObject("point").getString("long")
String lhg = jsonObject.getJSONObject("point").getString("lng") use "long" instead of lng.