如何使用json.net将复杂的json对象转换为CLR对象?

时间:2013-12-22 16:15:58

标签: c# json json.net

抱歉愚蠢的问题,但我没有找到任何解决办法。

这是我的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"
}

这是我的对象

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

如何 convert json string对象(带有内部对象)?

1 个答案:

答案 0 :(得分:1)

Json.Net需要一些帮助,因为你的json对象包含有效名称,这在c#中无效(Agent.Id

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

  

如何将json字符串转换为object(带有内部对象)?

由于你的json是扁平的(不包含子对象),你必须对你的反序列化对象进行后处理,如果你想这样使用/


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