sadlil
sadlil

Reputation: 3163

Reading and Writing a JSON file with Exact formate

I am working with a json file's sha:256 value. I have a json file, i need to read it and remove one specific element from the json value and write it back to the file. But the thing is i can't remove the formatting the file have, not even a whitespace, only the exact element. 1 white space removal cause different hash value. So i cant remove anything rather than the element. For an example :

JSON file:

{
    "a": "apple",
    "b": "ball",
    "c": "cat"
}

Then removing one element my file need to look like this:

{
    "a": "apple",
    "c": "cat"
}

How can I do this using Java?

Upvotes: 0

Views: 162

Answers (2)

sadlil
sadlil

Reputation: 3163

I have use jackson. And there is some PrettyPrinter methods that could formate the json as i wanted..

My Code:

  DefaultPrettyPrinter prettyPrinter = new DefaultPrettyPrinter();
  prettyPrinter.indentArraysWith(new DefaultIndenter("   ", DefaultIndenter.SYS_LF));
  prettyPrinter.indentObjectsWith(new DefaultIndenter("   ", DefaultIndenter.SYS_LF));
  String ret = mapper.writer(prettyPrinter).writeValueAsString(json);

Upvotes: 1

codeaholicguy
codeaholicguy

Reputation: 1691

You can deserialize json to a Map and remove key which you want to remove. After you serialize that Map to json and write it to the file. Example I use Gson for serialize and deserialize:

Deserialize:

String json = "{'a': 'apple', 'b': 'ball', 'c': 'cat'}";

Gson gson = new Gson();

Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(json, type);

Serialize:

gson.toJson(myMap)

Upvotes: 3

Related Questions