我如何反序列化JSON,其中有一个数组的ane/value属性以及有三个值的位置?



我正在尝试将一个HTTP请求反序列化为c# POCO类。

JSON是:

{
"applicationId":"4284f0b0-61f9-4a9d-8894-766f7b9605b5",
"deviceId":"testdevice22",
"messageType":"cloudPropertyChange",
"properties":[
{"name":"CustomerID","value":202},
{"name":"DeviceSerialNumber","value":"devicesa999"},
{"name":"Location","value":{
"alt":0,
"lat":41.29111465188208,
"lon":-80.91897192058899
}}
],
}

POCO为:

public class CustomEventModel
{
public string applicationId { get; set; }
public string deviceId { get; set; }
public List<PropertyAttribute> properties { get; set; }
}
public class PropertyAttribute
{
public string name { get; set; }
public string value { get; set; }
}

在我的功能应用程序我有:

string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
var propertyChangeData = JsonConvert.DeserializeObject<CustomEventModel>(requestBody);

异常消息是:2022-05-27T23:14:42.141 [Error] Error in CustomEventModel: Unexpected character encounter while parsing value:{。路径的属性[7]。值',第一行,

这些都与Location项相关。怎么解呢?

Location">

{
"alt":0,
"lat":41.29111465188208,
"lon":-80.91897192058899
}

这是一个复杂的对象,而另一个"values"不是。它们甚至不是同一种类型。一种解决方案是创建一个定制的反序列化器,如下所示:https://www.newtonsoft.com/json/help/html/CustomJsonConverterGeneric.htm

然后用自定义类型(例如CustomValue)编写从各种值类型的单向转换

public class CustomValueConverter : JsonConverter<CustomValue>
{
public override Version ReadJson(JsonReader reader, Type objectType, CustomValue existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var value = reader.Value;
return new CustomValue(value);
}
}

你的PropertyAttribute类现在看起来像这样:

public class PropertyAttribute
{
public PropertyAttribute() {}
public PropertyAttribute(object value)
{
//handle the various types of input in the constructor
}
public string name { get; set; }
public CustomValue value { get; set; }
}

现在可以使用自定义值转换器进行反序列化,如下所示:

var thing = JsonConvert.DeserializeObject<CustomEventModel>(json, new CustomValueConverter());

只需将value属性的类型从string更改为object,并添加Location类

public class PropertyAttribute
{
public string name { get; set; }
private object _value;
public object value
{
get
{
if (_value as JObject !=null)
return  ((JObject)_value).ToObject<Location>();
return _value?.ToString();
}
set { _value = value; }
}
}
public class Location
{
public int alt { get; set; }
public double lat { get; set; }
public double lon { get; set; }
}

如何使用

var propertyChangeData = JsonConvert.DeserializeObject<CustomEventModel>(requestBody);

Location location = (Location) propertyChangeData.properties.Where(p => p.name=="Location").FirstOrDefault().value;
string DeviceSerialNumber = (string) propertyChangeData.properties.Where(p => p.name=="DeviceSerialNumber").FirstOrDefault().value;

最新更新