简体   繁体   English

修改JSON-File并以与Java完全相同的顺序将其另存为文件

[英]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.. 我有一个要读取的json文件,然后修改特定键的值,然后以完全相同的顺序保存它。

I achieved the modification successfully, but in the JSONArray, now when writing it as JSON-File (JSONString), I get 2 problems: 我成功地完成了修改,但是在JSONArray中,现在将其编写为JSON-File(JSONString)时,遇到两个问题:

1) The order of the parameters (keys) change 1)参数(键)的顺序改变

2) The german-letters get encoded to weird characters.. 2)德语字母被编码为奇怪的字符。

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: 这是我的json文件的结构:

[{
    "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! 我只想修改detailsKey1的值! 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 ; JSON对象是根据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. 另外,虽然Java中的JsonArray库是按照此规范编写的,但您可以获取JSON中项目的索引,但是JsonWriter不允许您指定要插入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规范的解析器,那么再次需要的工作似乎超过了任何潜在的好处。

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 Json不会维护数据中对象的顺序...它在规范中。...请通过此链接获取更多信息... 链接

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... 关于编码问题,请尝试使用称为gson的Google json库。...下面的代码可以按原样打印数据...

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:: gson的maven依赖关系如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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