0

I receive a Json that looks like this:

[
  {
    "FieldName": "Note",
    "Value": "Test of a note"
  }, 
  {
    "FieldName": "P&IPayment",
    "Value": "Payment amount"
  }, 
  {
    "FieldName": "000-002",
    "Value": "ABC"
  }, 
]

I want to deserialize it to a class that looks like this:

    public class ExportModel
    {
        [Newtonsoft.Json.JsonPropertyAttribute("Note")]
        public string Note { get; set; }

        [Newtonsoft.Json.JsonPropertyAttribute("P&IPAYMENT")]
        public string PAndIPayment { get; set; }

        [Newtonsoft.Json.JsonPropertyAttribute("000-002")]
        public string MajorLoanType { get; set; }
    }

I want the FieldName to map to the attribute of the property and the Value to map to the property.

Thank you for any help.

cksanjose
  • 411
  • 1
  • 4
  • 14
  • 2
    What have you tried to solve your problem? – Pavel Anikhouski Jul 30 '20 at 19:35
  • 1
    There may be some fancy handlers you can give to JSON.NET to make it work this way, but I suspect it might be simpler to just deserialize the original JSON into objects with FieldName and Value properties, then turn those into a Dictionary, reserialize that Dictionary, then deserialize to the ExportModel. – StriplingWarrior Jul 30 '20 at 19:40
  • 1
    I already tried what @StriplingWarrior. I can work with but I'm hoping to use the properties. – cksanjose Jul 30 '20 at 19:45
  • 1
    The JSON shown here is invalid, as it is missing a quote after `ABC` and has a trailing comma (JSON does not allow them, even if ES6+ does). – Heretic Monkey Jul 30 '20 at 19:51

1 Answers1

1

You have to change the name of values:

[Newtonsoft.Json.JsonPropertyAttribute("Note")]
public string Note { get; set; } CHANGE FOR  ---> 
[Newtonsoft.Json.JsonPropertyAttribute("FieldName")]
public string FieldName { get; set; }


[Newtonsoft.Json.JsonPropertyAttribute("P&IPAYMENT")]
public string P&IPAYMENT{ get; set; } CHANGEFOR---> 
[Newtonsoft.Json.JsonPropertyAttribute("Value")]
public string Value{ get; set; }

And you have to delete these lines of code:

[Newtonsoft.Json.JsonPropertyAttribute("000-002")]
public string MajorLoanType { get; set; }
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 1
    I was successful in deserializing it to a class with FieldName and Value properties. What I'm attempting is the FieldName is mapped to the property and set it Value to it. – cksanjose Jul 30 '20 at 19:48
  • 1
    Welcome to Stack Overflow, and thanks for the answer. Here's primer on [how to format code and other things in Markdown](https://stackoverflow.com/help/formatting). Also, it's nice to explain what changes you've made to code, and why, to help not only the user asking the question, but later visitors as well. – Heretic Monkey Jul 30 '20 at 19:49
  • 1
    You can use the c# generic class and interfaces for do it. – Harold Cupitra Jul 30 '20 at 19:56