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?
CodePudding user response:
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
}
});
CodePudding user response:
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(Newtonsoft.Json.Formatting.Indented);
Output:
{
"ts": 1634712287000,
"values": {
"temperature": 26,
"humidity": 87
}
}
CodePudding user response:
To add the System.Text.Json Version:
using System;
using System.Text.Json;
public class Program
{
public static void Main()
{
var myAnonymousModel = new
{
Ts = 1634712287000,
Values = new
{
Temperature = 26,
Humidity = 87
}
};
var camelCasePolicyOptions =
new JsonSerializerOptions(){ PropertyNamingPolicy =
JsonNamingPolicy.CamelCase,
WriteIndented = true };
Console.WriteLine(
JsonSerializer.Serialize(myAnonymousModel,
camelCasePolicyOptions ));
}
}
Output:
{
"ts": 1634712287000,
"values": {
"temperature": 26,
"humidity": 87
}
}