使用动态键从请求体中初始化JSON

pokxtpni  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(64)

我有一个Rest API,它接受一个由动态GUID字段组成的JSON模型。
我尝试了多个模型,在所有这些模型中,我都得到了一个错误。
这就是JSON:

{
   "meta_data": {
       "name": "myname"
   },
   "1122413f-2887-4789-a112-31d003f2703a": {
       "ipadd": "1.1.1.1",
       "host": "host"
   },
   "4432313f-2887-4789-a222-31d41231233a": {
       "ipadd": "1.2.1.1",
       "host": "h3st"
   }
}

字符串
这就是模型

public class RootObject
{
    [JsonProperty("meta_data")]
    public Metadata Metadata { get; set; }

    public Dictionary<Guid, DeviceInfo> Devices { get; set; }
}

public class DeviceInfo
{
    public string IpAdd { get; set; }
    public string Host { get; set; }
}


以及控制器:

[FromBody] RootObject jsonObj


jsonObj仅包含Metadata,动态字段始终为空。
我能做些什么来克服这一点?
当我在Devices下发送时,它接受:

"Devices": { 
     "123...."
}


但这不是我需要的

r1zhe5dt

r1zhe5dt1#

如果您使用的是.NET Core 3及更高版本,则可以从 System.Text.Json.Serialization 使用JsonExtensionDataAttribute
您应该添加一个新的属性来接收额外的JSON元素Dictionary<string, JsonElement>
字典的TKey值必须为String,TValue必须为JsonElement或Object。
并通过一些数据转换将其分配给Devices属性。

using System.Text.Json.Serialization;
using System.Linq;

public class RootObject
{
    [JsonPropertyName("meta_data")]
    public Metadata Metadata { get; set; }

    [JsonExtensionData]
    public Dictionary<string, JsonElement> Extension { get; set; }
    
    [JsonIgnore]
    public Dictionary<Guid, DeviceInfo> Devices 
    { 
        get
        {
            if (Extension == null)
                return null;

            return Extension.ToDictionary(x => Guid.Parse(x.Key), v => JsonSerializer.Deserialize<DeviceInfo>(JsonSerializer.Serialize(v.Value)));
        }
    }
}

public class DeviceInfo
{
    [JsonPropertyName("ipadd")]
    public string IpAdd { get; set; }
    
    [JsonPropertyName("host")]
    public string Host { get; set; }
}

字符串
x1c 0d1x的数据
如果您使用 Newtonsoft.Json 作为API/MVC应用程序中的默认序列化库/工具:

services.AddControllers()
    .AddNewtonsoftJson();


您需要使用 * Newtonsoft.json * 中的属性/属性化方法。

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class RootObject
{
    [JsonProperty("meta_data")]
    public Metadata Metadata { get; set; }

    [JsonExtensionData]
    public Dictionary<string, JToken> Extension { get; set; }

    [JsonIgnore]
    public Dictionary<Guid, DeviceInfo> Devices
    {
        get
        {
            if (Extension == null)
                return null;

            return Extension.ToDictionary(x => Guid.Parse(x.Key), 
                v => JObject.FromObject(v.Value)
                    .ToObject<DeviceInfo>());
        }
    }
}

public class DeviceInfo
{
    [JsonProperty("ipadd")]
    public string IpAdd { get; set; }

    public string Host { get; set; }
}


相关问题