skip to Main Content

I have a JSON file like below, the first field has more than 500 values, how can I deserialize to C# class at bottom?

[
  {
    "E1001": { "MESSAGE": "", "CODE": 1001 }
  },
  {
    "E1002": { "MESSAGE": "", "CODE": 1002 }
  }
]
public class RootModel 
{
  public string ErrorCode { get; set; }
  public ErrorDetail Details { get; set; }
}

public class ErrorDetailModel 
{
  public string Message { get; set; }
  public string Code { get; set; }
}

2

Answers


  1. Chosen as BEST ANSWER

    I end up using AdditionalProperties, it will map all "un-mapped" values to JsonSchema object, JsonScheme give me List<key,value>, key is the error code, and value is { "MESSAGE": "", "CODE": 1001 }.

    https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Schema_JsonSchema_AdditionalProperties.htm


  2. you can use something like this

    List<RootModel> rootModels = JArray.Parse(json).Select(jo =>((JObject)jo).Properties().First())
                                                   .Select(prop =>   new RootModel {
                                                    ErrorCode = prop .Name,
                                                    Details=prop.Value.ToObject<ErrorDetail>()
                                                    }).ToList();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search