有时字符串有时反序列化JSON,有时反对c#

时间:2016-06-14 20:59:06

标签: c# api rest servicenow

您好我正在尝试向Json加载Sql Server回复。但Json可能是stringobject造成的。

以下是string

的示例
{
"result": [
    {
        "upon_approval": "proceed",
        "location": {
            "link": "https://satellite.service-now.com/api/now/table/cmn_location/4a2cf91b13f2de00322dd4a76144b090",
            "value": "4a2cf91b13f2de00322dd4a76144b090"
        }}]}

以下是object

的示例
{
    "result": [
        {
            "upon_approval": "proceed",
            "location": ""}]}

我的C#类就像

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace incident
{

    public class Location
    {
        public string link { get; set; }
        public string value { get; set; }
    }

    public class Result
    {
        public Location location { get; set; }
    }

    public class RootObject
    {
        public List<Result> result { get; set; }
    }
}

我正在使用Newtonsoft.Json。有一个简单的方法吗?

3 个答案:

答案 0 :(得分:1)

如果它作为空字符串发送,那么location对象将为null,因此使用c#6的示例可能是这样的:

var location = new Location
{
   Link = _request.Location?.Link,
   Value = _request.Location?.Value
}

答案 1 :(得分:1)

我真的不明白你的问题,因为你的代码似乎是正确的,但如果你只是想测试你的响应是一个Object还是一个简单的字符串,试着简单地得到它的类型:

if(yourResponse.GetType() == typeof(object) && yourResponse !=null) 
{
   //In this case, it's an Object, do the required treatment here
}
else if { yourResponse.GetType() == typeof(String) && yourResponse !=null &&  yourResponse != string.Empty) {

   //In this case, it's a string, do the required treatment here

}

当然,如果您的回答为空,您可以添加条件来进行特定治疗。

答案 2 :(得分:0)

  It is throwing me this error "Cannot convert object of type 'System.String' to type 'incident.Location" at this step in c# while debugging     JavaScriptSerializer ser = new JavaScriptSerializer();
            ser.MaxJsonLength = 2147483647;
            RootObject ro = ser.Deserialize<RootObject>(responseValue); @think2cecode1ce