-3

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; }
}
sinanorl
  • 143
  • 1
  • 9
DanielZ
  • 303
  • 3
  • 14
  • Does this answer your question? [Deserialize JSON with C#](https://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) – Jesse Dec 12 '22 at 20:51
  • 2
    Mostly a guess, but would a `Dictionary` work? – David Dec 12 '22 at 20:51
  • Not able to get Dictionary to work. This one is close: https://dotnetfiddle.net/z3KJj5 , but still require to know all the values first. – DanielZ Dec 12 '22 at 21:15
  • You question is absolutely unclear. What is the first and the second field? What is the difference between first and the second field. Can you show the bigger json, that we could see what do you mean? – Serge Dec 12 '22 at 21:50
  • Not quite sure what you're asking, but... the JSON doc you shared demonstrates an *anti-pattern* - you've stored actual values as your keys. This is going to cause a lot of issues, and you should consider rebuilding your JSON properly (e.g. something like `{ "ErrorString" : "E1001", "Message": "", "Code": 1001 }` – David Makogon Dec 12 '22 at 21:59
  • Also: You shouldn't be linking to additional details, in comments. All details should be in your question. – David Makogon Dec 12 '22 at 22:00
  • Deserialize to `List>`. Does that answer your question? – dbc Dec 13 '22 at 19:12

2 Answers2

0

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

DanielZ
  • 303
  • 3
  • 14
-1

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();
Serge
  • 40,935
  • 4
  • 18
  • 45