Gson Library Write in the file and only change a specific value - java

I'm currently using the Gson library to write/read a .json file. I have this method to write intro the json.
public static void write(String key, String value){
GeneralJsonConfig gjc = new GeneralJsonConfig();
if(key.equals("testKey")){
gjc.setaucString(value);
}
Gson gson = new Gson();
String json = gson.toJson(gjc);
try{
FileWriter fw = new FileWriter(launcherConfigFile);
fw.write(json);
fw.close();
} catch(IOException e) {
}
}
But lets say i have this .json:
{"testKey": "some test", "testKey2": "test 3"}
and i only want to change the thestKey from "some test" to another text and the other key/values will remain as they are now, but with my method the other values/key just dissaper, how can i solve this to make the other key/values stay ?
Update:
Found an answer based on sam100rav answer, i simply read the complete json file to get the vaules and then write them again with the changed that i want done:
public static void write(String key, String value){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try{
BufferedReader br = new BufferedReader(new FileReader(launcherConfigFile));
GeneralJsonConfig gjcObject = gson.fromJson(br, GeneralJsonConfig.class);
if(key.equals("testKey")){
gjc.setaucString(value);
}
String json = gson.toJson(gjcObject);
FileWriter fw = new FileWriter(launcherConfigFile);
fw.write(json);
fw.close();
br.close();
} catch (IOException e){
main.er.LogError("23", "");
}

JSONObject obj = new JSONObject();
obj.put("testKey", "some test");
obj.put("testKey2", "test 3");
if(key.equals("testKey")){
obj.put("testKey", value);
}
String json = obj.toString();
try{
FileWriter fw = new FileWriter(launcherConfigFile);
fw.write(json);
fw.close();
}

Found an answer based on sam100rav answer, i simply read the complete json file to get the vaules and then write them again with the changed that i want done:
public static void write(String key, String value){
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try{
BufferedReader br = new BufferedReader(new FileReader(launcherConfigFile));
GeneralJsonConfig gjcObject = gson.fromJson(br, GeneralJsonConfig.class);
if(key.equals("testKey")){
gjc.setaucString(value);
}
String json = gson.toJson(gjcObject);
FileWriter fw = new FileWriter(launcherConfigFile);
fw.write(json);
fw.close();
br.close();
} catch (IOException e){
main.er.LogError("23", "");
}

Related

Android Internal Storage: File is empty as soon as it has been read

So I am trying to save a HashMap as a JSON file into the internal storage of the app. This works well, as I can see in the device file explorer, everything is saved properly. When I then restart the app and read from the file it also works BUT after this one time reading the file is empty. Completely empty not even some "{}" when you save an empty JSON object.
public void writeNetworks(FileOutputStream fos) {
Log.d(TAG, "writeNetworks");
Gson gson = new GsonBuilder().create();
String json = gson.toJson(networks);
Log.d(TAG, json);
PrintWriter out = new PrintWriter(new OutputStreamWriter(fos));
out.println(json);
out.flush();
out.close();
}
public void readNetworks(FileInputStream fis) {
Log.d(TAG, "readNetworks");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
StringBuilder json = new StringBuilder();
String line;
while((line = in.readLine()) != null ) {
json.append(line);
}
in.close();
Log.d(TAG, json.toString());
Gson gson = new GsonBuilder().create();
Type typeOfHashMap = new TypeToken<Map<String, WrcUser>>() { }.getType();
networks = gson.fromJson(json.toString(), typeOfHashMap);
} catch (IOException e) {
e.printStackTrace();
}
}
Any ideas?
I actually found a way for it to work... I am now calling writeNetowrks(..) in the onStop() method of my activity. It seems to work consistent so far.

Read json file from resources and convert it into json string in JAVA [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have this JSON string hardcoded in my code.
String json = "{\n" +
" \"id\": 1,\n" +
" \"name\": \"Headphones\",\n" +
" \"price\": 1250.0,\n" +
" \"tags\": [\"home\", \"green\"]\n" +
"}\n"
;
I want to move this to resources folder and read it from there,
How can I do that in JAVA?
This - in my experience - is the most reliable pattern to read files from class path.[1]
Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")
It gives you an InputStream [2] which can be passed to most JSON Libraries.[3]
try(InputStream in=Thread.currentThread().getContextClassLoader().getResourceAsStream("YourJsonFile")){
//pass InputStream to JSON-Library, e.g. using Jackson
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(in, JsonNode.class);
String jsonString = mapper.writeValueAsString(jsonNode);
System.out.println(jsonString);
}
catch(Exception e){
throw new RuntimeException(e);
}
[1] Different ways of loading a file as an InputStream
[2] Try With Resources vs Try-Catch
[3] https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core
Move json to a file someName.json in resources folder.
{
id: 1,
name: "Headphones",
price: 1250.0,
tags: [
"home",
"green"
]
}
Read the json file like
File file = new File(
this.getClass().getClassLoader().getResource("someName.json").getFile()
);
Further you can use file object however you want to use. you can convert to a json object using your favourite json library.
For eg. using Jackson you can do
ObjectMapper mapper = new ObjectMapper();
SomeClass someClassObj = mapper.readValue(file, SomeClass.class);
There are many possible ways of doing this:
Read the file completely (only suitable for smaller files)
public static String readFileFromResources(String filename) throws URISyntaxException, IOException {
URL resource = YourClass.class.getClassLoader().getResource(filename);
byte[] bytes = Files.readAllBytes(Paths.get(resource.toURI()));
return new String(bytes);
}
Read in the file line by line (also suitable for larger files)
private static String readFileFromResources(String fileName) throws IOException {
URL resource = YourClass.class.getClassLoader().getResource(fileName);
if (resource == null)
throw new IllegalArgumentException("file is not found!");
StringBuilder fileContent = new StringBuilder();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(new File(resource.getFile())));
String line;
while ((line = bufferedReader.readLine()) != null) {
fileContent.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return fileContent.toString();
}
The most comfortable way is to use apache-commons.io
private static String readFileFromResources(String fileName) throws IOException {
return IOUtils.resourceToString(fileName, StandardCharsets.UTF_8);
}
Pass your file-path with from resources:
Example: If your resources -> folder_1 -> filename.json Then pass in
String json = getResource("folder_1/filename.json");
public String getResource(String resource) {
StringBuilder json = new StringBuilder();
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(Objects.requireNonNull(getClass().getClassLoader().getResourceAsStream(resource)),
StandardCharsets.UTF_8));
String str;
while ((str = in.readLine()) != null)
json.append(str);
in.close();
} catch (IOException e) {
throw new RuntimeException("Caught exception reading resource " + resource, e);
}
return json.toString();
}
There is JSON.simple is lightweight JSON processing library which can be used to read JSON or write JSON file.Try below code
public static void main(String[] args) {
JSONParser parser = new JSONParser();
try (Reader reader = new FileReader("test.json")) {
JSONObject jsonObject = (JSONObject) parser.parse(reader);
System.out.println(jsonObject);
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
try(InputStream inputStream =Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.MessageInput)){
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readValue(inputStream ,
JsonNode.class);
json = mapper.writeValueAsString(jsonNode);
}
catch(Exception e){
throw new RuntimeException(e);
}

JSONWriter add a new Line

I want to write several JSON Objects into a txt-file. For a better view I want that each object is in a different line and there is my problem: I don't know how to add a new line or seperate these objects.
Here is my code:
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("Item", item);
builder.add("Choice 1", idchoice1);
builder.add("Choice 2", idchoice2);
builder.add("Choice 3", idchoice3);
JsonObject jo = builder.build();
try {
FileWriter fw = new FileWriter("SelectedChoice.txt", true);
JsonWriter jsonWriter = Json.createWriter(fw);
jsonWriter.writeObject(jo);
jsonWriter.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
I hope you can help me to solve my problem.
Thanks to everyone!
EDIT:
Now I have seen that this structure in my file doesn't solve my problem.
I want to splitt several JSON Strings which are saved in this txt file and my code only converts the first JSON String in a JSON Object. Here my code:
try {
FileReader fr = new FileReader("SelectedChoice.txt");
BufferedReader br = new BufferedReader(fr);
String zeile ="";
while((zeile = br.readLine())!=null) {
System.out.println(zeile);
JSONObject choice = new JSONObject(zeile);
System.out.println(choice);
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I hope you can help me again!
You can use the pretty print option:
JsonObjectBuilder builder = Json.createObjectBuilder();
builder.add("Item", item);
builder.add("Choice 1", idchoice1);
builder.add("Choice 2", idchoice2);
builder.add("Choice 3", idchoice3);
JsonObject jo = builder.build();
try {
Map<String, Object> properties = new HashMap<>(1);
properties.put(JsonGenerator.PRETTY_PRINTING, true);
FileWriter fw = new FileWriter("SelectedChoice.txt", true);
JsonWriterFactory writerFactory = Json.createWriterFactory(properties);
JsonWriter jsonWriter = writerFactory.createWriter(fw);
jsonWriter.writeObject(jo);
jsonWriter.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}

parsing XML to base64 and json

I am trying to encode an XML to Base64 and then, write this Base64 to a JSON file.
When i do it, the Base64 is complete, but the JSON is incomplete, there is no trailing } at the end of string and it is incomplete, I do not know what could be do.
Here is my code:
This is the Xml to Base64 encoder
public static String fileEncoderBase64() throws IOException {
File file = new File("/root/EntradaN1.xml");
BufferedReader bufferedReader = null;
String linea;
String lineas = null;
try {
bufferedReader = new BufferedReader(new FileReader(file));
while ((linea = bufferedReader.readLine()) != null) {
lineas += linea;
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
bufferedReader.close();
}
return encodeBase64(lineas);
}
public static String encodeBase64(String mensaje) throws UnsupportedEncodingException {
byte[] bytes = mensaje.getBytes("UTF-8");
return Base64.getEncoder().encodeToString(bytes);
}
And this is the JSON parser:
public static void jsonCreator(JsonModelAgent jsonModelAgent) throws IOException {
Gson gson = new Gson();
gson.toJson(jsonModelAgent, new BufferedWriter(new FileWriter("/root/datos.json")));
}
And this is de diferences between mongo's Base64 length and json's length.
JSON: ==============>65176
MONGO: =============>76592
Thanks for help.
just adding close to jsonCreator's fileWriter works

Copying and appending Strings to json file in Android Studio

I have list of json files as below:
At the moment, T.json file is empty. All the other files already have some text. What I need is to create something like this:
1.At the beginning of the T.json file add sth like
{
"T": [
2.Copy text from e.g. T_Average.json and T_Easy.json to T.json file
3.At the end of T.json file add this:
]
}
So at the end of program execution I need to have in my T.json sth like:
{
"T": [
text from T_Average.json
text from T_Easy.json
]
}
So how can I add text from 1st and 3rd step to the file?
And how can I copy everything from other files to T.json file?
I have already tried some solutions like this:
try(FileWriter fw = new FileWriter("T.json", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println("the text");
out.println("more text");
} catch (IOException e) {
//exception handling left as an exercise for the reader
}
or like this one:
try {
String data = " This is new content";
File file = new File(FILENAME);
if (!file.exists()) {
file.createNewFile();
}
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
but all the time, after line with fw = new FileWriter() it was jumping right to the catch clause.
So one more time:
How can I add text from 1st and 3rd step to the file?
And how can I copy everything from other files to T.json file?
Thanks :)
Try
1. Add following methods getJsonFromAssetFile and writeFile to your code
2. Read json file
String content = getJsonFromAssetFile("T_Difficult.json");
3 Create final json (as mentioned)
JSONObject finalJson = new JSONObject();
try {
JSONObject jsonObject = new JSONObject(content);
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject);
finalJson.put("T", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
4. Write final json to file
writeFile(finalJson.toString().getBytes());
writeFile
public static void writeFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = null;
try {
FileOutputStream fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data);
}
finally {
if (bos != null) {
try {
bos.flush ();
bos.close ();
}
catch (Exception e) {
}
}
}
}
getJsonFromAssetFile
public static String getJsonFromAssetFile(Context context, String jsonFileName) {
String json = null;
try {
InputStream is = context.getAssets().open(jsonFileName);
int size = is.available ();
byte[] buffer = new byte[size];
is.read (buffer);
is.close ();
json = new String(buffer, "UTF-8");
}
catch(IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
NOTE: Read json asset file using getJsonFromAssetFile method and Write file on internal/external storage and provide proper path to writeFile method

Categories