Search code examples
c#json.net

Could not determine JSON object type for anonymous type


I am trying to create a JSON object which should look like this when converted into a string:

{
    "ts":1634712287000,
    "values":{
        "temperature":26,
        "humidity":87
    }
}

This is how I tried to do it by creating a Newtonsoft.Json.Linq.JObject:

new JObject(new
{
    Ts = 1634712287000,
    Values = new JObject(new
    {
        Temperature = 26,
        Humidity = 87
    }),
});

With this code I get the following error:

Could not determine JSON object type for type <>f__AnonymousType2`2[System.Int32,System.Int32]."}   System.ArgumentException

I am obviously doing something wrong but I cannot figure out how to do this correctly. What am I doing wrong and how can I create a JObject like in my example above via code?


Solution

  • You need to create the whole anonymous object first, and then you can convert it, so:

    var obj = new {
        ts = 1634712287000,
        values = new {
            temperature = 26,
            humidity = 87
        },
    };
    
    // var json = JObject.FromObject(obj).ToString(Formatting.Indented);
    
    var json = JsonConvert.SerializeObject(data, Formatting.Indented);
    

    Output:

    {
      "ts": 1634712287000,
      "values": {
        "temperature": 26,
        "humidity": 87
      }
    }
    

    Edit:

    As pointed out by @JoshSutterfield in the comments, using the serializer here is more efficient than using JObject - benchmark:

    | Method        | Mean       | Error    | StdDev   | Median     | Gen0   | Gen1   | Allocated |
    |-------------- |-----------:|---------:|---------:|-----------:|-------:|-------:|----------:|
    | UseJObject    | 1,158.1 ns | 16.15 ns | 14.32 ns | 1,161.3 ns | 0.4597 | 0.0019 |   3.76 KB |
    | UseSerializer |   458.8 ns | 22.73 ns | 67.02 ns |   425.9 ns | 0.2055 | 0.0005 |   1.68 KB |