0

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.

ZelelB
  • 1,836
  • 7
  • 45
  • 71
  • is your `keys` and `detailedkeys` are fixed in numbers (i mean 1 to 4 only). If it is so then only i can provide a solution to it – Vikrant Kashyap Apr 22 '16 at 10:59
  • one more suggestion to you. please use `switch` rather than `if`. Switch will reduce your complexity . Thankx – Vikrant Kashyap Apr 22 '16 at 11:09
  • Please post your readFile method. I suspect your issue with German chars is due to encoding. You should be using a Reader with the right Chartset. Or, if this is Jackson, you should just pass an InputStream and let Jackson decode it - see http://wiki.fasterxml.com/JacksonBestPracticesPerformance#A3._Use_the_.22least_processed.22_forms_of_input_source – AngerClown Apr 22 '16 at 11:15
  • no.. that was just an example to show you how the structure of the json is, and how it should be kept.. – ZelelB Apr 22 '16 at 11:15

2 Answers2

0

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.

0

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>
Community
  • 1
  • 1
Abhishek
  • 2,485
  • 2
  • 18
  • 25