简体   繁体   中英

Modify JSON-File and save it back as a file in exactly the same order with Java

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.

JSON objects are unordered sets of name/value pairs according to the JSON Spec ; so I would question the need for this feature firstly.

In addition, while the JsonArray library in java is written to this spec you can get the index of items in the JSON, but JsonWriter will not let you specify an index to insert into the JSON.

If order is a necessity, I would suggest writing your own parser that does not conform to the JSON spec, then again the effort required seems to outweigh any potential benefit.

Json will not maintain the ordering of the objects in the data... it is in it's specification.... please go through this link about more information... link

And about the encoding issue try using google's json library known as gson.... The below code work's fine in printing the data as is...

public static void main(String[] args) {
    HashMap<String, String> a = new HashMap<String, String>();
    a.put("über dreißig", "mäßig term here");
    System.out.println(new Gson().toJson(a));
}

the maven dependencies for gson is as follows::

<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.2.2</version>
</dependency>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM