无法确定匿名类型的 JSON 对象类型

问题描述 投票:0回答:3

我正在尝试创建一个 JSON 对象,转换为字符串时应如下所示:

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

这就是我尝试通过创建一个

Newtonsoft.Json.Linq.JObject
来做到这一点:

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

使用此代码,我收到以下错误:

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

我显然做错了什么,但我不知道如何正确地做到这一点。 我做错了什么以及如何通过代码创建像上面的示例中那样的

JObject

c# json .net
3个回答
5
投票

你需要先创建整个匿名对象,然后才能转换它,所以:

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);

输出:

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

编辑:

正如 @JoshSutterfield 在评论中善意指出的那样,这里使用

JObject
的效率低于仅使用序列化器 - 基准测试:

| 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 |

2
投票

如果您不想创建类,我们可以尝试将 Json.NET 与匿名对象一起使用。

var jsonData = JsonConvert.SerializeObject(new {
    ts = 1634712287000,
    Values = new {
        Temperature = 26,
        Humidity = 87
    }
});

2
投票

添加 System.Text.Json 版本:

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 ));   
    }
}

输出:

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

参见https://dotnetfiddle.net/JPUJRv

© www.soinside.com 2019 - 2024. All rights reserved.