从响应

时间:2017-01-05 14:16:06

标签: c# .net json

我收到来自Json格式的第三方服务的回复。这些字段几乎相同,除非验证失败,否则会导致程序崩溃。 Json回来了

{
    "response": 0,
    "sites": {
        "site": {
            "customer": [{
                "validation": {
                    "customer.dob": "dob required",
                    "customer.surname": "surname required"
                }
            }]
        }
    },
    "records": {
        "insertcount": 0,
        "deletecount": 0
    },
    "referrals": []
}

并且

{
    "sucession": 0,
    "sites": {
        "site": "please try later."
    },
    "records": {
        "insertcount": 0,
        "deletecount": 0
    },
    "referrals": []
}

要阅读Json,我使用在线工具为上述Json创建一个类,然后我将其去除它

RootObject ro = JsonConvert.DeserializeObject<RootObject>(JsonInStringFormat);

我如何构建这个以便一个类可以相应地处理Json?或者有另一种方法可以做同样的事情吗?返回的Json保存在字符串变量中(注意JsonInStringFormat

编辑 - RootObject

public class RootObject
{
    public int response { get; set; }
    public Sites sites { get; set; }
    public Records records { get; set; }
    public List<object> referrals { get; set; }
}

2 个答案:

答案 0 :(得分:1)

using System.Web.Script.Serialization;

namespace ThirdPartyJSON
{
    class Program
    {
        static void Main()
        {
            string jsonString = System.IO.File.ReadAllText("thirdparty.json");

            var serial = new JavaScriptSerializer();

            var o = serial.Deserialize<Rootobject>(jsonString);
        }
    }

    public class Rootobject
    {
        public int response { get; set; }
        public Sites sites { get; set; }
        public Records records { get; set; }
        public object[] referrals { get; set; }
        public int sucession { get; set; }
    }

    public class Sites
    {
        public object site { get; set; }
    }

    public class Site
    {
        public Customer[] customer { get; set; }
    }

    public class Customer
    {
        public Validation validation { get; set; }
    }

    public class Validation
    {
        public string customerdob { get; set; }
        public string customersurname { get; set; }
    }

    public class Records
    {
        public int insertcount { get; set; }
        public int deletecount { get; set; }
    }
}

这似乎有效 - 因为所有内容都来自&#34; object&#34;。添加&#39; sucession&#39;在Rootobject类中也是如此。所以现在它是双重目的。我对这一切都很陌生,如果我的回答不正确,那就很抱歉。只是想帮忙。

答案 1 :(得分:0)

如果您的根对象更改了响应,则应使用dynamic objects作为反序列化的结果,如here所示。

在你的情况下:

C#:

dynamic data = JsonConvert.DeserializeObject(JsonInStringFormat);
if (data.sucession == 0) //checking the dynamic object for this property
{
    //here you already know "sites" has no values
    //do what you have to
}
else
{
    //success!
    RootObject ro = JsonConvert.DeserializeObject<RootObject>(JsonInStringFormat);
    Sites test = ro.sites; //sites values retrieved!
}