parse a json file lost structure of data - JAVA - java

i have to create a json file that contain some object (a name, a string list and a date list). the problem is when i have to write and read date in LocalDate format.
if i write and then i print the jsonObject, the format of the date is ok. but when i do the parse and suddedly i print the object, the format of the date is wrong.
this is the code for write in the file:
public void aggiungi(){
JSONObject obj = new JSONObject();
obj.put("name", this.name);
JSONArray listMov = new JSONArray();
JSONArray listData = new JSONArray();
for(int i =0; i<this.movimenti.size(); i++){
listMov.add(movimenti.get(i));
listData.add(data.get(i));
}
obj.put("data", listData);
obj.put("mov", listMov);
File file=new File("file.json");
try {
file.createNewFile();
FileWriter fileWriter = new FileWriter(file);
fileWriter.write(obj.toJSONString());
fileWriter.flush();
fileWriter.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(obj);
}
and the final println print:
{"data":[2015-03-02,2015-04-05,2015-06-10],"mov":
["F24","PagoBancomat","Bollettino"],"name":"Stefano"}
and this is the code for read:
JSONParser parser = new JSONParser();//per decodifica
Object obj;
try {
obj = parser.parse(new FileReader("file.json"));
JSONObject jsonObj = (JSONObject) obj;
String name= (String) jsonObj.get("name");
JSONArray list = (JSONArray) jsonObj.get("mov");
JSONArray listData = (JSONArray) jsonObj.get("data");
System.out.println(jsonObj);
Iterator<String> iteratorM = list.iterator();
Iterator<LocalDate> iteratorD = listData.iterator();
ArrayList<String> mov =new ArrayList<String>(list.size());
ArrayList<LocalDate> data =new ArrayList<LocalDate>(list.size());
while(iteratorM.hasNext()){
mov.add(iteratorM.next());
}
while(iteratorD.hasNext()){
data.add(iteratorD.next());
}
ContoCorrente cc = new ContoCorrente(data, mov, name);
Contatore task = new Contatore(cc);
this.executeTask(task);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and print
{"data":[2015,-3,-2,2015,-4,-5,2015,-6,-10],"mov":
["F24","PagoBancomat","Bollettino"],"name":"Stefano"}
the last print separes the structure of a date, separing day, month and year.
what i do wrong in the code?
thanks you and sorry for my bad english

Instead of setting as a data object in JSON,first parse it to String using dateformatters then set it in JSON object as string.

Use DateTimeFormatter for converting LocalDate into String value, assuming data as object of ArrayList<LocalDate> ;
JSONArray listMov = new JSONArray();
JSONArray listData = new JSONArray();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
for(int i =0; i<this.movimenti.size(); i++){
listMov.add(movimenti.get(i));
listData.add(data.get(i).format(formatter));
}

Related

How to post this type of data in JSON Object

I have to post this type of data into Json. I don't want to convert cat in string. I only want single quote of item enclosing with double quote.
{"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
My Json
JSONObject jsonobject1 = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
jsonobject.put("ovpsc7s", jsonobject1);
jsonobject1.put("cat", hCategory);
Here hCategory is Hashset.
I want to json like this
{"p02bvsd":"cal_dis","ovpsc7s":{"cat": ["'Furniture'", "'Bikes'", "'Others'" ]}}
JSONObject jsonobject = new JSONObject();
jsonobject.put("p02bvsd", "cal_dis");
JSONObject jsonobject1 = new JSONObject();
List <String> list = new ArrayList <String>();
list.add("Furniture");
list.add("Bikes");
list.add("Others");
JSONArray array = new JSONArray();
for (int i = 0; i < list.size(); i++) {
array.put(list.get(i));
}
try {
jsonobject1.put("cat", array);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonobject.put("ovpsc7s", jsonobject1);
String myString = "{\"p02bvsd\":\"cal_dis\",\"ovpsc7s\":{\"cat\":[\"\'Furniture\'\", \"\'Bikes\'\", \"\'Others\'\"]}}";
JSONObject wholeThing = new JSONObject(myString); // contains {"p02bvsd":"cal_dis","ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}}
JSONObject jsonp02bvsd = wholeThing.getJSONObject("p02bvsd"); // contains {"p02bvsd":"cal_dis"}
JSONObject jsonovpsc7s = wholeThing.getJSONObject("ovpsc7s"); // contains {"ovpsc7s":{"cat":["'Furniture'", "'Bikes'", "'Others'"]}
JSONArray jsonCatArray = jsonp02bvsd.getJSONArray("cat"); // contains ["'Furniture'", "'Bikes'", "'Others'"]
String first = jsonCatArray.getString(0); // contains 'Furniture'

Why does the following string show a JSONException?

The following code generates a org.json.JSONException: No value for eqlocation.
https://jsonformatter.curiousconcept.com/ doesn't show any error for the string.
String message="{"eqlocation": [{"lat": 38.3904, "lon": 73.8278}, {"lat": 19.0119, "lon": 95.5838}, {"lat": 12.9046, "lon": 92.2347}, {"lat": 34.1968, "lon": 80.7091}], "cydata": []}";
try {
JSONObject jsonObj = new JSONObject(message);
Log.v("fromjson",jsonObj.get("eqlocation").toString());
}
catch (JSONException e){
e.printStackTrace();
Toast.makeText(getContext(),"No JSON received",Toast.LENGTH_SHORT).show();
}
You need to escape the quotes inside the string and you can use a parser to simplify the proccess.
JSONParser parser = new JSONParser();
String message = "{\"eqlocation\":[{\"lat\":38.3904,\"lon\":73.8278},{\"lat\":19.0119,\"lon\":95.5838},{\"lat\":12.9046,\"lon\":92.2347},{\"lat\":34.1968,\"lon\":80.7091}],\"cydata\":[]}";
try {
Object obj = parser.parse(message);
JSONObject obj2 = (JSONObject) obj;
Log.v("fromjson",obj2.get("eqlocation").toString());
}
catch (ParseException pe){
pe.printStackTrace();
}
}
You can see it working in plain java here: https://repl.it/repls/InvolvedSuperbSupport
The json looks fine but you're trying to parse an Array data.
Instead, you can try this:
try {
JSONObject jsonObj = new JSONObject(message);
JSONArray jArray = jsonObj.getJSONArray("eqlocation"); // get the array
for(int i=0; i < jArray.length(); i++) { // loop through the items
JSONObject json_data = jArray.getJSONObject(i);
Log.v("fromjson", json_data.getString("lat")); // get latitute here
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getContext(),"No JSON received",Toast.LENGTH_SHORT).show();
}
Note: However, the way you initialized the String is not correct. You'll need to escape the quotes.

getJSONObject not working in Java

I'm trying to parse json file in my java project using this below code,
JSONParser parser = new JSONParser();
try {
Object obj = null;
try {
obj = parser.parse(new FileReader(new File("json/branch_list.json")));
} catch (org.json.simple.parser.ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
System.out.println("Branches are :");
JSONArray listOfBranches = (JSONArray) jsonObject.get("branch_list");
Iterator iterator = listOfBranches.iterator();
for (int i = 0; i < listOfBranches.size(); i++) {
JSONObject c = listOfBranches.getJSONObject(i);
System.out.println("Branch are :" + listOfBranches.get(i));
}
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
From above code when i'm using this two below lines
JSONObject c = listOfBranches.getJSONObject(i);
String branchName = c.getString("branch_name");
Its shows the method getJSONObject(int) is undefined for the type JSONArray
And I'm getting the whole object when using this below code,
System.out.println("Branch are :"+listOfBranches.get(i));
It prints like this,
{"branch_name":"AMM"}
from this I want to get branch name using the key "branch_name". But I could not able to do this because of "the method getJSONObject(int) is undefined for the type JSONArray" exception
And I have added json-simple jar in my project. Could you please suggest me any idea to do this? Thanks in advance.
If i undestood you right then:
JSONObject item = (JSONObject)listOfBranches.get(0);
String branchName = (String)item.get("branch_name");
i think you should use org.json instead of simple-json. The method getJSONObject(i) is available in org.json. Refer to the below url for more detail.
https://stackoverflow.com/questions/2591098/how-to-parse-json

how to extract a multiple json objects within objects

I'm trying to read a list of episodes (http://epguides.frecar.no/show/bigbangtheory/) from a json file, count the episode titles and print them in the console. However since I'm new to working with json I can't even manage to reach the first title, always returning null. A little help or a small hint towards the right direction would be greatly appreciated.
JSONParser parser = new JSONParser();
try {
File tmpDir = new File("src/bigbangtheory.json");
boolean exists = tmpDir.exists();
if (exists==true) System.out.println("file exists");
else System.out.println("file doesn't exist");
Object obj = parser.parse(new FileReader("src/bigbangtheory.json"));
JSONObject season = (JSONObject) obj;
System.out.println(obj);
Object title = (Object) season.get("title");
System.out.println(title);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (org.json.simple.parser.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The JSON file contains an object holding all seasons.
From that object you need to extract a specific season and episode before you're able to read a title.
Object obj = parser.parse(new FileReader("src/bigbangtheory.json"));
JSONObject seasons = (JSONObject) obj;
System.out.println(seasons);
JSONArray seasonTwo = (JSONArray) seasons.get("2");
System.out.println(seasonTwo);
for (Object o : seasonTwo) {
JSONObject episode = (JSONObject) o;
Object title = episode.get("title");
System.out.println(title);
}

Writing JSON object to file writes unwanted character

I'm trying to write JSON object to file which consists of JSONArray. Before writing this object to TXT file I check each structure printing it in console. For example I got this out put:
{"splittedHostEnteredString":["cześć.","w"],"foreignLanguage":"cześć","historyToWord":"cześć. w","mainLanguage":"jak","country":0}
In list I have for example 10 objects like above and each of them prints correctly. Problem is when I try to write ArrayList which has all objects as strings. File writes also but after it, there are some additional characters - "\" in all structure. I convert object to string using GSON library. Below is the output after saving file:
{"names":["{\"splittedHostEnteredString\":[\"cześć.\",\"każdym\"],\"foreignLanguage\":\"jak\",\"historyToWord\":\"cześć. w każdym razie\",\"mainLanguage\":\"z\",\"country\":0}","{\"splittedHostEnteredString\":[\"cześć.\",\"w\"],\"foreignLanguage\":\"cześć\",\"historyToWord\":\"cześć. w\",\"mainLanguage\":\"jak\",\"country\":0}"]}
This is my code:
public void saveListOfExistingObjectsInApplicationToOneFileJson()
{
String filename = "configuration.txt";
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
try {
myFile.createNewFile();
JSONObject obj = new JSONObject();
try {
JSONArray array = new JSONArray();
for(int i = 0; i < listOfSavedFiles.size(); i++)
{
array.put(listOfSavedFiles.get(i));
}
obj.put("names", array);
System.out.println(obj.toString());
String tmpStringToWrite = obj.toString();
FileOutputStream stream = new FileOutputStream(myFile);
try {
stream.write(tmpStringToWrite.getBytes());
} finally {
stream.close();
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

Categories