Gson append new object array to existing JSON file - java

i need some help appending new arrays into a existing file. I have a JSON file like this:
[
{
"name": "any",
"address": {
"street": "xxxx",
"number": 1
},
"email": "teste#gmail.com"
}
]
I want to insert new array, so my file will be like this:
[
{
"name": "any",
"address": {
"street": "xxxx",
"number": 1
},
"email": "test#gmail.com"
},
{
"name": "any2",
"address": {
"street": "yyyyy",
"number": 2
},
"email": "test2#gmail.com"
}
]
Here's my code:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
ArrayList<Person> ps = new ArrayList<Person>();
// .... reading entries...
ps.add(new Person(name, address, email));
String JsonPerson = gson.toJson(ps);
File f = new File("jsonfile");
if (f.exists() && !f.isDirectory()) {
JsonReader jsonfile = new JsonReader(new FileReader("jsonfile"));
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(jsonfile);
//here goes the new entry?
try (FileWriter file = new FileWriter("pessoas.json")) {
file.write(JsonPessoa);
file.close();
} catch (Exception e) {
e.printStackTrace();
}
So, what's the best way to do this?
Thanks in advance.

Gson really shines when combined with Pojos, so my suggestion would be use of mapped pojos. Consider below two classes.
public class Contact {
#SerializedName("address")
private Address mAddress;
#SerializedName("email")
private String mEmail;
#SerializedName("name")
private String mName;
// getters and setters...
}
public class Address {
#SerializedName("number")
private Long mNumber;
#SerializedName("street")
private String mStreet;
// getters and setters...
}
Read JSON and add new contact and convert it back to JSON, It also works for other way around seamlessly. Similarly you can use this approach for solve many use cases. Pass json array string by reading from file or using similar way, after
Gson gson = new Gson();
List<Contact> contacts = gson.fromJson("JSON STRING", new TypeToken<List<Contact>>() {}.getType());
Contact newContact = new Contact();
// set properties
contacts.add(newContact);
String json = gson.toJson(contacts);
There are tools like this one to create pojos from JSON.

Related

Writing to a JSON file

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

Java - How to get all the field names from JSON Schema

{
"type": "TestType",
"schema": {
"type": "object",
"properties": {
"field1": {
"format": "date",
"label": "field 1",
"type": "string"
},
"field2": {
"format": "date",
"label": "field 2",
"type": "string"
}
},
"required": [],
"additionalProperties": false
}
}
Hi Guys, I am new to JSON Schema, I just want to know how to define the Java model to mapping above JSON Schema, I want to get all the field name from the definition.
So it means that I want to parse the JSON Schema and return like this:
[field1, field2]
Note that the field list is automatic, may add more fields into the JSON Schema, field3, field4 ...
1.convert to JSONObject
2.save in List
3.convert List to Array
try this .
public void getKey(String response) {
List<String> keyList = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject schema = jsonObject.getJSONObject("schema");
JSONObject properties = schema.getJSONObject("properties");
Iterator iterator = properties.keys();
while (iterator.hasNext()) {
String key = iterator.next().toString();
keyList.add(key);
}
String[] arr = (String[]) keyList.toArray(new String[keyList.size()]);
} catch (JSONException e) {
e.printStackTrace();
}
}
I assume your json is in a String variable named var.
use org.json for the below code.
JSONObject jObj=new JSONObject(var);
ArrayList arr=new ArrayList();
for (Object keyObj: jObj.keySet())
{
String key = (String)keyObject;
arr.add(key);
}
That's it.
I have added maven dependency for org.json package for those who are working with maven!
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160810</version>
</dependency>
Recursive solution that will work with nested objects
public Set<String> getMetadataSchemaFields(JsonNode metadataSchema) {
if (metadataSchema.has("properties")) {
val fields = new HashSet<String>();
metadataSchema.get("properties").fields().forEachRemaining(entry -> {
val nodeFields = getMetadataSchemaFields(entry.getValue());
if (nodeFields.isEmpty()) {
fields.add(entry.getKey());
} else {
nodeFields.forEach(nodeField -> fields.add(entry.getKey() + "/" + nodeField));
}
});
return fields;
} else {
return Set.of();
}
}

Parse nested Json object and store in database in Android

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

Getting JSON value from HTTP Request using GSON with Java

I need to get the lat and lng cords as separate string values. I decided to use GSON to help with this but am having issues getting the points. I'd prefer not to add any extra classes but it's not a deal breaker. I don't even care to use an easier solution without GSON if there is one.
Below is what I tried.
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws InterruptedException, IOException, JSONException {
JSONObject json = readJsonFromUrl("http://open.mapquestapi.com/geocoding/v1/address?key=Fmjtd|luu821ual9,8w=o5-94aaqy&location=1448south4thstreetlouisvilleky");
System.out.println(json.toString());
System.out.println(json.get("results"));
}
I can get the results string but not just the lat or lng. Plus it uses extra classes I was trying to avoid. Below is what the JSON returned from the URL looks like.
{
"info": {},
"options": {},
"results": [
{
"providedLocation": {
"location": "address here"
},
"locations": [
{
"street": "address here",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "city name",
"adminArea5Type": "City",
"adminArea4": "County name",
"adminArea4Type": "County",
"adminArea3": "State name",
"adminArea3Type": "State",
"adminArea1": "US",
"adminArea1Type": "Country",
"postalCode": "zip here",
"geocodeQualityCode": "P1AAX",
"geocodeQuality": "POINT",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 90.227222,
"lng": -90.762007
},
"displayLatLng": {
"lat": 90.227222,
"lng": -90.762007
},
"mapUrl": "http://open.mapquestapi.com/staticmap/v4/getmap?key=111111111,160&pois=purple4"
}
]
}
]
}
JsonParser parser = new JsonParser();
JsonObject o = parser.parse(jsonStr).getAsJsonObject();
JsonElement latLng = o.get("results")
.getAsJsonArray().get(0)
.getAsJsonObject().get("locations")
.getAsJsonArray().get(0)
.getAsJsonObject().get("latLng");
Parse json String as Jsonobject, and get value one by one. but I think the fastest way is creating a model to map the Json String Object.

How to parse the json object with multiple keys in android

I want to put the JSON result in textviews but because of multiple array i can get only one key/value of datetime, location and status objects. The json object is:
{
"signature":"testSignature",
"deliverydate":"2015-08-06 15:07:00",
"datetime":{
"0":1438848420,
"1":1438841820,
"2":1438838760,
},
"location":{
"0":"PA",
"1":"PA",
"2":"PA",
},
"status":{
"0":"packed",
"1":"On the go",
"2":"delivered",
},
"pickupdate":2015-08-04 07:55:00
}
and this is my java code:
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("NO", NUMBER_TO_POST));
JSONObject json = jsonParser.makeHttpRequest(URL_TO_POST, "POST", params);
success = json.getString(TAG_SIGNATURE);
if (success != null) {
SIGNATURE = json.getString(TAG_SIGNATURE);
DELIVERY_DATE = json.getString(TAG_DELIVERY_DATE);
JSONObject DT = json.getJSONObject(TAG_DATETIME);
DATETIME = DT.getString("0");
JSONObject LOC = json.getJSONObject(TAG_LOCATION);
LOCATION = LOC.getString("0");
JSONObject STAT = json.getJSONObject(TAG_STATUS);
STATUS = STAT.getString("0");
PICKUP_DATE = json.getString(TAG_PICKUP_DATE);
}else{
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
can anyone help me to solve this? Thanks
You should use GSON library to parse JSONs.
And to be a bit more helpful, here is how your class to hold JSON values might look like:
class MyClassForGsonToHoldParseJSON {
String signature;
String deliverydate;
Map<String, long> datetime;
Map<String, String> location;
Map<String, String> status;
String pickupdate;
}
Then just use something like this to conver variable json with JSON data to an object:
Gson gson = new Gson();
MyClassForGsonToHoldParseJSON f = gson.fromJson(json, MyClassForGsonToHoldParseJSON.class);
Your JSON format is wrong:
{
"signature": "testSignature",
"deliverydate": "2015-08-06 15:07:00",
"datetime": {
"0": 1438848420,
"1": 1438841820,
"2": 1438838760
},
"location": {
"0": "PA",
"1": "PA",
"2": "PA"
},
"status": {
"0": "packed",
"1": "On the go",
"2": "delivered"
},
"pickupdate": " 2015-08-04 07:55:00"
}

Categories

Resources