Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not determine JSON object type for anonymous type

Tags:

json

c#

.net

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?

like image 882
Chris Avatar asked Oct 18 '25 13:10

Chris


2 Answers

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 |
like image 71
stuartd Avatar answered Oct 20 '25 03:10

stuartd


We can try to use Json.NET with an anonymous object if you don't want to create a class.

var jsonData = JsonConvert.SerializeObject(new {
    ts = 1634712287000,
    Values = new {
        Temperature = 26,
        Humidity = 87
    }
});
like image 43
D-Shih Avatar answered Oct 20 '25 02:10

D-Shih



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!