Reputation: 37
These are the data contract class and attributes below.
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;
}
This is the JSON code where I'm getting the issue and is after the "ModelState" where no field name is given.
How do I create data Contract classes to reflect the JSON below?
{"Message":"The request is invalid.","ModelState":{"":["Some messege is being displayed"]}}
EDIT Code to proccess deserialization:
Stream res= await response.Content.ReadAsStreamAsync();
var x = await response.Content.ReadAsStringAsync();
object result= ModelStateSerializer.ReadObject(res);
Upvotes: 1
Views: 859
Reputation: 247123
Using the following class structure
public partial class ValidationErrors {
public string Message { get; set; }
public ModelState ModelState { get; set; }
}
public partial class ModelState : Dictionary<string, List<string>> {
}
The following example demonstrates how to use Json.Net to generate the desired JSON described in the original question.
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);
}
Output:
{"Message":"The request is invalid.","ModelState":{"":["Some messege is being displayed"]}}
The output JSON is able to be deserialized to the same class structure used in the serialization.
The following example reads the content of a response and converts it to the desired type.
var json = await response.Content.ReadAsStringAsync();
var errors = JsonConvert.DeserializeObject<ValidationErrors>(json);
var message = errors.Message;
var modelState = errors.ModelState;
var details = modelState[""].FirstOrDefault();
Upvotes: 1