0

I am using Gson in my project and a I have a Json file that's built like this:

{
  "123.123.123": {
    "port": 1234,
    "type": 'c'
  },
  "124.124.124": {
    "port": 1244,
    "type": 'f'
  }
}

I want to add a record (IP, port, and type) to this file, without rewriting the whole file, how would I do that with Gson?

Similar to this question, and the comment on the answer.

SwagiWagi
  • 411
  • 5
  • 17
  • Does [this](https://stackoverflow.com/questions/22585970/how-to-add-an-object-as-a-property-of-a-jsonobject-object) answer your question ..? – Barbaros Özhan Oct 04 '20 at 11:29
  • 1
    Does this answer your question? [How to add an object as a property of a JsonObject object?](https://stackoverflow.com/questions/22585970/how-to-add-an-object-as-a-property-of-a-jsonobject-object) – Nowhere Man Oct 04 '20 at 11:31
  • Not exactly, I would like to know how can I append only the new record and not rewriting the whole file. – SwagiWagi Oct 04 '20 at 12:12
  • There just is no easy way to use random access write with files. As [stated here](https://stackoverflow.com/a/410331/6413377) as an aswer to a similar question. Eventually you need to append at the end of file with some parsing magic to keep it as a valid JSON or write the whole file. Gson is not designed for random file access. – pirho Oct 04 '20 at 17:18
  • @pirho Then I believe I will use a CSV for that, as it is more like a DB. – SwagiWagi Oct 04 '20 at 17:21
  • Well, I can not see how that would resolve the underlying problem. That is why there are SQL & NoSQL, databases, for example. CSV is no database, it is just a vague format to present data. It would not either write anything in the middle of the file. Maybe it is easier to use what comes to appending at the end of the file. – pirho Oct 04 '20 at 17:26
  • @pirho Yea well, I would have used an actual DB if I could, but I need to use plain files. CSV is easier in the way that you can just write to the end of the file instead of having to rewrite the ending '}' in the JSON. Anyway, it solved my problem. – SwagiWagi Oct 04 '20 at 20:55
  • @SwagiWagi As an alternative approach giving you more flexibility (no schema, nested values, nulls, etc) comparing to CSV, you could also take a look at JSON streaming techniques described at https://en.wikipedia.org/wiki/JSON_streaming . Line-delimited, record-delimited, and concatenated JSON documents support can be easily built on top of Gson. Not sure about line-prefixed JSON documents in regards to Gson though (might require reading/writing underlying streams in lenient mode). – terrorrussia-keeps-killing Oct 05 '20 at 07:54
  • @fluffy That's actually really cool, but as I have ended up using CSV I understood that JSON is really not intended for a DB like use, but more for responses kind of use. – SwagiWagi Oct 06 '20 at 11:58

0 Answers0