我如何将这个JSON字符串表示为C#中的对象

时间:2019-12-30 14:39:43

标签: c# json .net-4.0

API想要的JSON

{
  "$type": "Asi.Soa.Membership.DataContracts.PersonData, Asi.Contracts",
  "PersonName": {
    "$type": "Asi.Soa.Membership.DataContracts.PersonNameData, Asi.Contracts",
    "FirstName": "",
    "LastName": "",
    "MiddleName": ""
  },
  "AdditionalAttributes": {
    "$type": "Asi.Soa.Membership.DataContracts.PersonData, Asi.Contracts",
    "Name": "",
    "value": ""
  },
  "Addresses": {
    "$type": "Asi.Soa.Membership.DataContracts.FullAddressData, Asi.Contracts",
    "Address": {
      "$type": "Asi.Soa.Membership.DataContracts.AddressData, Asi.Soa.Membership.Contracts",
      "AddressLines": [
        "",
        ""
      ],
      "AddressPurpose": "Main Address"
    }
  }
}

我如何最好地用C#表示这一点。我正在努力解决它的多维方面。

我已经尝试过类似的事情,但是一旦嵌套对象,我就会出错。

            object json = new object
            {
                "json" : new object {
                    "$type": "Asi.Soa.Membership.DataContracts.PersonData, Asi.Soa.Membership.Contracts",
                    "PersonName" : "stuff"
                },
            };

1 个答案:

答案 0 :(得分:0)

没有$ type属性,您可以创建一个匿名类型并使用Json.NET:

var loObject = new
{
    json = new
    {
        PersonName = new
        {
            FirstName = "Tyler",
            LastName = "Durden",
            MiddleName = "From Paper Street"
        },
        AdditionalAttributes = new
        {
            Name = "accessoires",
            Value = "glasses"
        }
    }
};
string lsOut = JsonConvert.SerializeObject(loObject);

使用$ type属性,您必须创建一个类层次结构并使用[JsonProperty("$type")] 参见:https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm

或者您可以使用类似的东西:

var loObject = new
{
    PersonName = new Dictionary<string, string>
    {
        { "$type", "Asi.Soa.Membership.DataContracts.PersonData, Asi.Contract" },
        { "FirstName", "Tyler" },
        { "LastName", "Durden" },
        { "MiddleName", "" }
    },
    AdditionalAttributes = new
    {
        Name = "accessoires",
        Value = "glasses"
    },
    Addresses = new Dictionary<string, object>
    {
        { "$type", "Asi.Soa.Membership.DataContracts.PersonData, Asi.Contract" },
        {
            "Address", new string[]{ "537 Paper Street", "Bradford 19808" }
        }
    }
};