I have a json-file that I want to read, and then modify the value of a specific key, and then save it in exactly the same order..
I achieved the modification successfully, but in the JSONArray, now when writing it as JSON-File (JSONString), I get 2 problems:
1) The order of the parameters (keys) change
2) The german-letters get encoded to weird characters..
So how can I do the modification with saving the changes in exactly the same order they were read, and letting the german-characters as they are?
Here is the structure of my json-file:
[{
"key1": "key here",
"key2": "key2 here",
"key3": "pId here11",
"details": {
"detailsKey1": "https://linkHere.com/conf/conf1/conf2/img/testImage.png",
"detailsKey2": "desc here",
"detailsKey3": "some url here",
"detailsKeys4": "some key here",
"terms": [{
"termsKey1": "über dreißig",
"termsKey2": "mäßig term here"
}]
}
}, {
"key1": "key here",
"key2": "key2 here",
"key3": "pId here11",
"details": {
"detailsKey1": "https://linkHere.com/conf/conf1/conf2/img/testImage.png",
"detailsKey2": "desc here",
"detailsKey3": "some url here",
"detailsKeys4": "some key here",
"terms": [{
"termsKey1": "über dreißig",
"termsKey2": "mäßig term here"
}]
}
}]
I want to modify just the detailsKey1's value! I want to change that link for every object in my file, with a new string.
Here is my code:
public class testi {
public static void main(String[] args) throws JSONException, IOException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
String jsonOldData = readFile("C:\\Users\\myuser\\Desktop\\img.json");
JSONArray jOldArray = new JSONArray(jsonOldData);
ArrayList<String> myOldArray = new ArrayList<>();
System.out.println("length old: " + jOldArray.length());
for(int i=0; i < jOldArray.length(); i++) {
System.out.println("link here" + i + ": " + jOldArray.getJSONObject(i).getJSONObject("details").getString("detailsKey1"));
if (i == 0) {
jOldArray.getJSONObject(i).getJSONObject("details").put("detailsKey1", "testImage.png");
System.out.println("NEW teaserImage " + i + ": " + jOldArray.getJSONObject(i).getJSONObject("details").getString("detailsKey1"));
}
if (i==2)
System.out.println("teaserImage " + (i-2) + ": " + jOldArray.getJSONObject(i-2).getJSONObject("details").getString("detailsKey1"));
}
}
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
}
As you can see/test, the change take place in the Array, but I dont know how to go further now, to get my new (updated) file saved in my Desktop, with the same keys oder.