how to append to json file in java - java

I have this js.json file
i want to add another block to the file.
the file now ->
[
{
"diff":"Easy",
"qus":"John1"
}
]
how i want it to be ->
[
{
"diff":"Easy",
"qus":"John1"
},
{
"diff":"Avg",
"qus":"John2"
}
]

You can use org.json library as follow:
JSONArray jsonarray = new JSONArray(jsonStr); //from the file
JSONObject jsonobject = new JSONObject(yourNewlyJsonObject);
jsonarray.put(jsonobject);
System.out.println(jsonarray.toString()); // or write it back to the file

you can check this code.
JSONObject obj = new JSONObject({
"diff":"Avg",
"qus":"John2"
});
JSONArray a = (JSONArray) parser.parse(new FileReader("c:\\exer4-courses.json")); // reading the file and creating a json array of it.
a.put(obj); // adding your created object into the array
// writing the JSONObject into a file(info.json)
try {
FileWriter fileWriter = new FileWriter("c:\\exer4-courses.json"); // writing back to the file
fileWriter.write(a.toJSONString());
fileWriter.flush();
} catch (Exception e) {
e.printStackTrace();
}
References:
https://www.javatpoint.com/json-tutorial
http://www.vogella.com/tutorials/JavaIO/article.html

Related

Get specific value from JSON array using java

I want to fetch only PersonNumber value from below JSON sample using java.
{"Context":[{"PersonNumber":"10","DMLOperation":"UPDATE","PeriodType":"E","PersonName":"Ponce","WorkerType":"EMP","PersonId":"1000","PrimaryPhoneNumber":"1","EffectiveStartDate":"2018-01-27","EffectiveDate":"2018-01-27"}],"Changed Attributes":[{"NamInformation1":{"new":"Ponce","old":"PONCE"}},{"FirstName":{"new":"Jorge","old":"JORGE"}},{"LastName":{"new":"Ponce","old":"PONCE"}}]}
Below is my code:
for (SyndContentImpl content : (List<SyndContentImpl>) entry.getContents()) {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(content.getValue().toString());
System.out.println(jsonObj.get("Context"));
} catch (JSONException e) {
e.printStackTrace();
} }
You have to access to the path Context[0].PersonNumber.
This can be done with
String personNumber = jsonObj.getJSONArray("Context").getJSONObject(0).getString("PersonNumber");

Getting JSON values from a .json

I am currently writing a program that pulls weather info from openweathermaps api. It returns a JSON string such as this:
{"coord":{"lon":-95.94,"lat":41.26},"weather":[{"id":500,"main":"Rain","description":"light
rain","icon":"10n"}],"base":"stations","main": ...more json
I have this method below which writes the string to a .json and allows me to get the values from it.
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.get("weather"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}
The problem is it only allows me to get the outer values such as "coord" and "weather". So currently since I have System.out.println(Jobj.get("weather")); it will return [{"icon":"10n","description":"light rain","main":"Rain","id":500}] but I want to actually get the values that are inside of that like the description value and the main value. I haven't worked much with JSONs so there may be something obvious I am missing. Any ideas on how I would do this?
You can use JsonPath (https://github.com/json-path/JsonPath) to extract some json field/values directly.
var json = "{\"coord\":{\"lon\":\"-95.94\",\"lat\":\"41.26\"},\n" +
" \"weather\":[{\"id\":\"500\",\"main\":\"Rain\",\"description\":\"light\"}]}";
var main = JsonPath.read(json, "$.weather[0].main"); // Rain
you can use
JSONObject Jobj = (JSONObject) obj;
System.out.println(Jobj.getJSONObject("coord").get("lon");//here coord is json object
System.out.println(Jobj.getJSONArray("weather").get(0).get("description");//for array
or you can declare user defined class according to structure and convert code using GSON
Gson gson= new Gson();
MyWeatherClass weather= gson.fromJSON(Jobj .toString(),MyWeatherClass.class);
System.out.println(weather.getCoord());
From the json sample that you have provided it can be seen that the "weather" actually is an array of objects, so you will have to treat it as such in code to get individual objects from the array when converted to Jsonobject.
Try something like :
public String readJSON() {
JSONParser parse = new JSONParser();
String ret = "";
try {
FileReader reader = new FileReader("C:\\Users\\mattm\\Desktop\\Java Libs\\JSON.json");
Object obj = parse.parse(reader);
JSONObject jobj = (JSONObject) obj;
JSONArray jobjWeatherArray = jobj.getJSONArray("weather")
for (int i = 0; i < jobjWeatherArray.length(); i++) {
JSONObject jobjWeather = jobjWeatherArray.getJSONObject(i);
System.out.println(jobjWeather.get("id"));
System.out.println(jobjWeather.get("main"));
System.out.println(jobjWeather.get("description"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(ret);
return ret;
}

Why do I have 98 lines instead of 99?

I have a directory named json which contains 99 json files.
The files are named: sentiment_i.json where i is an incremental integer starting from 1.
I wrote some code to read some content from each of these files and write said content in a txt file with one line for each json file.
public static void main(String[] args) throws Exception, IOException, ParseException {
String type ="";
ArrayList<String> sentiment = new ArrayList<String>();
int i= 1;
double score = 0;
File dir = new File("json");
File[] directoryListing = dir.listFiles();
JSONObject jsonObject;
if (directoryListing != null) {
for (File child : directoryListing) {
JSONParser parser = new JSONParser();
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
i++;
continue;
}
JSONObject doc = (JSONObject) jsonObject.get("docSentiment"); // get the nested object first
type = (String)doc.get("type"); // get a string from the nested object
// CODICE PER PRENDERE ANCHE LO SCORE
if (!(type.equals("neutral"))){
score = (double) doc.get("score");
} else score = 0;
sentiment.add(type+";"+score);
i++;
}
}
PrintWriter out = new PrintWriter("sentiment.txt");
for(String value: sentiment)
out.println(value);
out.close();
}
}
The problem is that I get 98 lines in my txt file even if there are 99 json files in the directory.
I've been trying to find the bug for an hour now but I'm going nuts!
Hope you can help me, thanks.
EDIT: Woah the downvotes :(
Anyway, maybe I was not clear. The point has never been catching and dealing with the missing file!
Also
jsonObject = (JSONObject) parser.parse(new FileReader(child))
in my case is not useful at all and let me explain why.
In the json folder, as stated, there json files named like this: "sentiment_1", "sentiment_2" and so on.
In the folder there are let's say 1000 of these but not every number from 1 to 1000 is there.
If you rely on FileReader(child), in the for loop the files are not read in the correct order (1,2,3,4...)!
This happens because for the sorting order in the folder, for example 10 comes before than 2 because the order is 1,10,2,3,4....
So, as clearly the downvoters didn't understand at all, the problem is not that easy at it seems.
It's not about a simple loop problem lol.
Because of this block of code:
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
i++;
continue;
}
Which is omitting the error from you, use this instead:
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
I believe you have a missformatted json file name:
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
i++;
continue;
}
This block of code tells that, if a file is not found, it is just ignored without any console feedback.
Replace by :
try {
jsonObject = (JSONObject) parser.parse(new FileReader("json/sentiment_"+i+".json"));
} catch (FileNotFoundException e) {
System.out.println("Missing json file: " + e.getMessage());
i++;
continue;
}
You will have an idea about what is going on.
A better solution
Currently you are looping through files but you never use the current iteration, you are using an i variable. A FileReader can be instanciated with a File instead of the file path as a string:
try {
jsonObject = (JSONObject) parser.parse(new FileReader(child));
} catch (FileNotFoundException e) {
System.out.println("Missing json file: " + e.getMessage());
i++;
continue;
}

Create a JSON Object using java

I am new to JSON creations . I want to create a JSON object for each element in the for-each loop. My code is like
for(int i=0 ; i<=childclasses.size() ;i++ ){
for (OInstance oinstance:oinstances){
oinstancelist.add(oinstance);
}
}
try {
object.put("subclass",oclass);
object.put("instance", oinstancelist);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("json is " +object);
I want to create a json object for every oinstance . So,How can i do that ?
With Gson, creating a JSON-String is as easy as:
Gson gson = new Gson();
String json = gson.toJson(oinstance);
GSON is good and always faster then JSON.
However for JSON, Get json-simple-1.1.1.jar and add into your classpath and write below logic to create JSON object
import org.json.simple.JSONObject;
class JsonEncodeDemo {
public static void main(String[] args){
JSONObject obj = new JSONObject();
obj.put("name", "jsonObject");
obj.put("num", new Integer(100));
obj.put("balance", new Double(1000.21));
obj.put("is_vip", new Boolean(true));
System.out.print(obj);
}
}
You will get output like : {"balance": 1000.21, "num":100, "is_vip":true, "name":"jsonObject"}
However, as you are new to JSON you can visit this also.

GSON how to parse array with dynamic type

Looking at this Json file, KEY is always a String, but VALUE sometimes is a String but sometimes is an typed object with two String fields.
How can I parse it using GSON?
{
"property": [
{
"key": "key_A",
"value": "value_A"
},
{
"key": "key_B",
"value": "value_B"
},
{
"key": "key_C",
"value": {
"param_C_1": "value_C_1",
"param_C_2": "value_C_2"
}
}
]
}
The first thing is parsing this json file to java that can be done
this way :-
try {
InputStream is;
//read the whole json file stored in assets
//below is android way of opening file from local resource folder, you can use other means to open
is = getApplicationContext().getAssets().open("jsonfile.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
//convert the json file to string
String bufferString = new String(buffer);
JSONObject jsonObject;
JSONArray jsonArray;
jsonObject = new JSONObject(bufferString);
jsonArray=jsonObject.getJSONArray("property");
for (int i=0;i<jsonArray.length();i++){
jsonObject = jsonArray.getJSONObject(i);
JSONObject s = jsonArray.optJSONObject(i);
String s2 = s.getString("value");
if(s2.contains("{")){
JSONObject jobject = new JSONObject(s2);
String valueUnderValue1 = jobject.getString("param_C_1");
String valueUnderValue2 = jobject.getString("param_C_2");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Then make a class which will have all the values you got from the json file.
Say that class is MyClass, containing all of the values you got from json file.
make MyClass object and then
MyClass obj = new MyClass();
Gson gson = new Gson();
JSONObject onj = new JSONObject();
JSONArray userDataValues = new JSONArray();
//again convert to json
userDataValues.put(new JSONObject(gson.toJson(obj)));
//serialized the object
onj.put("property", userDataValues);
I hope this is what you want.

Categories

Resources