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

那年仲夏 提交于 2020-01-03 03:33:05

问题


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": "gena@email.com",
    "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)?


回答1:


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; }
}


来源:https://stackoverflow.com/questions/20731389/how-do-i-convert-a-complex-json-object-to-clr-object-with-json-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!