这些是下面的数据协定类和属性。
public partial class ValidationErrors
{
[System.Runtime.Serialization.DataMemberAttribute()]
public string Message;
[System.Runtime.Serialization.DataMemberAttribute()]
public ModelState ModelState;
}
[System.Runtime.Serialization.DataContractAttribute()]
public partial class ModelState
{
[System.Runtime.Serialization.DataMemberAttribute()]
public string[] empty;
}
这是我遇到问题的JSON代码,位于“ ModelState”之后,未提供任何字段名称。
如何创建数据合同类以反映下面的JSON?
{"Message":"The request is invalid.","ModelState":{"":["Some messege is being displayed"]}}
EDIT 进行反序列化的代码:
Stream res= await response.Content.ReadAsStreamAsync();
var x = await response.Content.ReadAsStringAsync();
object result= ModelStateSerializer.ReadObject(res);
答案 0 :(得分:1)
使用以下类结构
public partial class ValidationErrors {
public string Message { get; set; }
public ModelState ModelState { get; set; }
}
public partial class ModelState : Dictionary<string, List<string>> {
}
以下示例演示了如何使用 Json.Net 生成原始问题中描述的所需JSON。
public static void Main()
{
var errors = new ValidationErrors {
Message = "The request is invalid.",
ModelState = new ModelState {
{ "", new List<string>(){"Some messege is being displayed"} }
}
};
var json = JsonConvert.SerializeObject(errors);
Console.WriteLine(json);
}
输出:
{"Message":"The request is invalid.","ModelState":{"":["Some messege is being displayed"]}}
输出JSON可以反序列化为序列化中使用的相同类结构。
下面的示例读取响应的内容,并将其转换为所需的类型。
var json = await response.Content.ReadAsStringAsync();
var errors = JsonConvert.DeserializeObject<ValidationErrors>(json);
var message = errors.Message;
var modelState = errors.ModelState;
var details = modelState[""].FirstOrDefault();