2

I have a C# program and I am trying to serialize some of my items as JSON array to be compatible with dygraphs. However, I cannot figure out how to do it, all the examples I find are about deserialization. My object is:

{
    "file": {
        "header" : {
            "param1" : "test",
            "param2" : "test2"
         },
        "points": [
            {
                "timestamp": "47602070",
                "s1": "4",
                "s2": "3",
            },
            {
                "timestamp": "47602370",
                "s1": "-4",
                "s2": "2",
            }
        ]
    }
}

What I would need would be:

{
    "file": {
        "header" : {
            "param1" : "test",
            "param2" : "test2"
         },
        "points": [
            ["47602070","4","3"]
            ["47602370","-4","2"]
        ]
    }
}

Basically, converting all the Point objects to array while serializing. Is this something easily doable with JSON.NET custom converter ?

Kind regards

Valentin
  • 81
  • 6
  • 4
    Answer is Yes. Did you try? – PepitoSh Jul 25 '18 at 07:54
  • @PepitoSh I tried with a very naive approach (basically just reading the values and creating a new JArray), but I was not able to implement it fully, I think I am not understanding quite well how the writer work. Also, it did not work at all when my List of Point was nested in another element like in this example. – Valentin Jul 25 '18 at 08:13
  • 1
    @AndyJ I want to do the reverse (serializing) but the answer from the question you mentioned may help as it implements a Write function too. I will give it a try. – Valentin Jul 25 '18 at 08:16
  • I think you can do this (both writing and reading) using `ObjectToArrayConverter` from [C# JSON.NET - Deserialize response that uses an unusual data structure](https://stackoverflow.com/a/39462464/3744182). – dbc Jul 25 '18 at 08:19
  • serializing is literally mapping the properties in the text (JSON in this case) to properties in an object. It's a literal one to one mapping. So if you want to change the data structure, that's something you would do after you've serialised. Possibly libraries like JSON.NET provide ways to streamline that process and make it less visible to you with things like custom converters, but likely that's what is physically happening behind the curtain. – ADyson Jul 25 '18 at 08:21
  • `ObjectToArrayConverter` from [C# JSON.NET - Deserialize response that uses an unusual data structure](https://stackoverflow.com/a/39462464/3744182) does work for both deserialization and serialization, see https://dotnetfiddle.net/Ng1mtP – dbc Jul 25 '18 at 08:25

0 Answers0