hackp0int
hackp0int

Reputation: 4161

How do I convert a complex json object to CLR object with json.net?

sorry for a dumb question but I haven't found any solution for this.

Here is my JSON:

{
    "Id": "1",
    "Parent.Id": "1",
    "Agent.Id": "1",
    "Agent.Profile.FullName": "gena",
    "Fee": "10.1200",
    "FeeManagementDate": "29/11/2013",
    "Contact.Name": "Genady",
    "Contact.Telephone": "000000000",
    "Contact.Email": "[email protected]",
    "AgreementUrl": "http://www.test.com/agreement"
}

Here is my object

 public class ManagementDetailsViewModel : ViewModel<int> {
    public ManagementDetailsViewModel() {

    }
    public string AgreementUrl { get; set; }


    public HttpPostedFileBase AgreementFile { get; set; }


    public decimal Fee { get; set; } // payment data

    public DateTime? FeeDate { get; set; }


    public string FeeManagementDate {
        get { return FeeDate != null ? FeeDate.Value.ToString("dd/MM/yyyy") : DateTime.Now.ToString("dd/MM/yyyy"); }
        set {
            FeeDate = Convert.ToDateTime(value);
        }
    }

    public BusinessViewModel Parent { get; set; }
    public MemberViewModel Agent { get; set; }
    public Contact Contact { get; set; }
}

How do I convert the json string to object (with inner objects)?

Upvotes: 1

Views: 702

Answers (1)

L.B
L.B

Reputation: 116138

Json.Net needs some help because your json object contain propery names, which is not valid in c# like(Agent.Id)

var obj  = JsonConvert.DeserializeObject<MyObj>(json);

How do I convert the json string to object (with inner objects)?

Since your json is flat(not containing sub objects) you have to post process your deserialized object if you want to use it that way/


public class MyObj
{
    public string Id { get; set; }

    [JsonProperty("Parent.Id")]
    public string ParentId { get; set; }

    [JsonProperty("Agent.Id")]
    public string AgentId { get; set; }

    [JsonProperty("Agent.Profile.FullName")]
    public string ProfileFullName { get; set; }

    public string Fee { get; set; }

    public string FeeManagementDate { get; set; }

    [JsonProperty("Contact.Name")]
    public string ContactName { get; set; }

    [JsonProperty("Contact.Telephone")]
    public string ContactTelephone { get; set; }

    [JsonProperty("Contact.Email")]
    public string ContactEmail { get; set; }

    public string AgreementUrl { get; set; }
}

Upvotes: 1

Related Questions