Adding backup feature on my app and i am using Realm database, i want to backup it to a json file.
i have created the function for reading the database and create a JSONobject.
While doing the JSONobject.tostring i got a outofmemory error since i have more than 200'000 records.
any other way to create the json file.
RealmResults<StoneModelR> allStones = realm.where(StoneModelR.class).sort("id", Sort.ASCENDING).findAll();
for (StoneModelR singleStone : allStones) {
try {
JSONObject jObjectStone = new JSONObject();
jObjectStone.put("stoneid", singleStone.id);
jObjectStone.put("lat", singleStone.lat);
jObjectStone.put("lng", singleStone.lon);
jObjectStone.put("userid", singleStone.userid);
jObjectStone.put("owner", singleStone.owner);
jObjectStone.put("timestamp", singleStone.timestamp);
jObjectStone.put("stonetype", singleStone.stonetype);
jObjectStone.put("remarks", singleStone.description);
jObjectStone.put("imported", singleStone.imported);
jArrayStones.put(jObjectStone);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JSONObject stoneObj = new JSONObject();
try {
stoneObj.put("stones", jArrayStones);
} catch (JSONException e) {
e.printStackTrace();
}
Related
I would like to create a Json structure manually using JsonObject and JsonArrays like the below:
{
"data":[
{
"company_name":"xyz",
"Amount":"$2000",
"Duplicate_amount":"$500"
},
{
"company_name":"abc",
"Amount":"$5000"
},
{
"company_name":"zzz",
"Amount":"$2500",
"Duplicate_amount":"$1000"
}
]
}
The Json above is to be generated based on a checking done on an Arraylist. For example: Arraylist [xyz,abc,zzz,xyz,hhh,zzz]. Now I want to check, if the arraylist contains duplicate elements i.e here "xyz" and "zzz" then in the Json structure, the Duplicate_amount Json object to be added in the Json. Else if no duplicate present then only "company_name" and "amount" to be formed. The whole json format to be formed in this way.
How to do it? I have the logic for finding duplicate elements. But I cannot seem to find the logic for forming the above json based on the checking.
Thank you
Updates
So far I have tried this with checking. But the below code doesn't work and is not forming the appropriate json. What is the solution ?:
JSONObject root_jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject sub_jsonobj= new JSONObject();
Object[] st = AppData.customer_arr.toArray();
for (Object s : st) {
//The if-else is the duplicate checking part here
if (AppData.customer_arr.indexOf(s) != AppData.customer_arr.lastIndexOf(s)) {
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("dup_amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
jsonArr.put(sub_jsonobj);
counter++;
}
try {
root_jsonObj.put("data", jsonArr);
} catch (Exception e) {
e.printStackTrace();
}
You can use this one.
JSONObject obj1 = new JSONObject();
try {
obj1.put("company_name", "xyz");
obj1.put("Amount", "$2000");
obj1.put("Duplicate_amount", "$500");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject obj2 = new JSONObject();
try {
obj2.put("company_name", "xyz");
obj2.put("Amount", "$2000");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj1);
jsonArray.put(obj2);
JSONObject dataObj = new JSONObject();
dataObj.put("Data", jsonArray);
String jsonStr = dataObj.toString();
System.out.println("jsonString: "+jsonStr);
I see an old method from a colleague of deserializing json object in java where the json is taken as string deserialized and passed the values in an array. What I dont understand about this code is why for every field try and catch method is added and why can't we have a single try and catch because all catch do the same thing of catching the json exception and assigning responseArray[0] to value 1.
Here is the code:
String[] responseArray = new String[4];
Arrays.fill(responseArray, "");
try {
final JSONObject response1 = new JSONObject(response);
try{
responseArray[0] = response1.getJSONObject("body")
.getJSONObject("responseStatus").getString("estado");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
if(!responseArray[0].equalsIgnoreCase("0")){
try{
responseArray[1] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("codigoRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
try{
responseArray[2] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("descripcionRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
}
try{
responseArray[3] = response1.getJSONObject("body")
.getJSONObject("responseData").getLong("esValido")+"";
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
} catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
return responseArray;
There is no explicit need to add try and catch blocks to every ".getJSONObject" methods.
There are two ways by which you can use exception handling.
1. try-catch blocks. Single try & catch block would work fine as well.
2. Let the method throws JSONException as a replacement to try and catch blocks.
Checked exceptions (like the one in your case) are checked at compile time, and so you need to handle them using either of the two ways
Exception handling reference link
I would like to leverage nested object indexing in Elastic Search. I know how to do that with PUT requests through curl (https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-mapping.html) but I would like to do that through Java API instead.
Here is how I create dynamically my index
public void index(AnObject obj){
Client client = elasticService.getES();
// generate json
if (client != null){
try {
byte[] json = JSON.serializeAsBytes(obj);
IndexResponse response = client.prepareIndex("titan", "objIndex", obj.getUuid())
.setSource(json)
.get();
} catch (ElasticsearchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
and here is how I update it
public void updateIndex(AnObject obj){
Client client = elasticService.getES();
// generate json
if (client != null){
try {
byte[] json = JSON.serializeAsBytes(obj);
UpdateResponse response = client.prepareUpdate("titan", "objIndex", obj.getUuid())
.setDoc(json)
.get();
} catch (ElasticsearchException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I wonder if there is a way to set my index through Java so that specific or all of the embedded objects are mapped as nested
If that is not possible is it possible to configure Elastic search default mapping to index everything as datatype nested?
Any help is appreciated! Thanks!
hi i want to parse my downloaded json file that stored in the SDCard directory ,
i don't know how can i do that !
im google a lot but i can only find somethings like : BuffredReader , InputFileStream , ...
please help me !
here is part of my code but it have the problem i attached in the image :
File GroupsJsonFileAdress = new File(Enviroments.getExternalStorageDirectory() + "FOLDER/G.json");
try {
ObjectInputStream groupsInJson = new ObjectInputStream(new FileInputStream(GroupsJsonFileAdress));
JSONObject jsonObject = (JSONObject)groupsInJson.readObject();
String DATABASE_VERSION = jsonObject.getString("DBVersion");
JSONArray groupsArray = jsonObject.getJSONArray("Groups");
for (int i = 0; i < groupsArray.length(); i++) {
JSONObject groupJsonObjectReader = groupsArray.getJSONObject(i);
int id= groupJsonObjectReader.getInt("Id");
String gTitle = groupJsonObjectReader.getString("title");
Group loaderG = new Group();
loaderG.GroupId = id;
loaderG.Title = gTitle;
Log.i("INFO", loaderG.Title);
groupsClasses.add(loaderG);
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
and here is the error i got :
http://i.stack.imgur.com/lQ3YN.jpg
Create a model that matches your Json architecture and then parse it using GSON librarie ;)
Easiest way to do it so far for me :)
i'm struggling with a JSONObject. I allready returned some json and converted it succesfully to objects and list of objects. My now i'm stuck.
This is the JSONObject i'm getting:
{"Result":true,"Messages":["Goe bezig!"]}
I'm able to get the Messages, but i can't seem to get the boolean in Result. Can somebody explain how to get it plz?
Here is the code:
public boolean Convert(JSONObject json) {
try
{
return json.getBoolean("Result");
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
This worked fine for me, although it's pretty vague your question.
String jsonString = "{\"Result\":true,\"Messages\":[\"Goe bezig!\"]}";
JSONObject jsonObject = new JSONObject(jsonString);
boolean result = (Boolean) jsonObject.get("Result");
System.out.println(result);
You might want to catch at the end of your method Exception as well:
try {
return json.getBoolean("Result");
} catch (JSONException e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
} catch (Exception e) {
e.printStackTrace(); // replace these with `Log` statement
return false;
}