2016-06-14 3 views
-1

안녕하세요 Sql ServerJson 응답을로드하려고합니다. 그러나 Jsonstring 또는 object 일 수 있습니다. 여기 때때로 JSON 문자열을 역 직렬화 할 때 때때로 C#

{ 
"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; } 
    } 
} 
같이이다 : 여기

그것이 string 때 예입니다

Newtonsoft.Json을 사용하고 있습니다. 이 작업을 수행하는 쉬운 방법이 있습니까? 난 정말이 문제를 이해하지 못하는

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

코드에는 아무런 문제가 없습니다. 'Result.Location'는'JSON'에 빈 문자열이 있으면 null이됩니다. deserialization에는 아무런 문제가 없습니다. 귀하의 질문은 무엇인가? – niksofteng

+0

JavaScript를 디버깅하는 동안 C#의이 단계에서 'System.String'유형의 객체를 'incident.Location'을 입력 할 수 없습니다.이 오류가 발생합니다. ser = new JavaScriptSerializer(); ser.MaxJsonLength = 2147483647; RootObject ro = ser.Deserialize (responseValue); –

+0

JavaScript를 디버깅하는 동안 C#의이 단계에서 'System.String'유형의 객체를 'incident.Location'을 입력 할 수 없습니다.이 오류가 발생합니다. ser = new JavaScriptSerializer(); ser.MaxJsonLength = 2147483647; RootObject ro = ser.Deserialize (responseValue); think2cecode1ce –

답변

1

다음 위치 객체가 null이됩니다, 그래서 C# 6을 사용하는 예제가 될 수있다 당신은 당신의 코드가 잘 될 것 같다 있기 때문에,하지만 당신은 단순히 당신의 응답이 객체 또는 간단한 문자열 인 경우 테스트하려는 경우, 단순히 같은 그 형태 얻으려고 : 당신은 조건을 추가 할 수 있습니다, 물론

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 

} 

을 특정 일을하는 귀하의 응답이 null 인 경우 fic 치료.

+0

답변 해 주셔서 감사합니다. 예, null 값입니다. 작성한 코드는 ia m을 (를) 이해할 수 없습니다 .net. C# 코드에 추가하십시오. @chandler –

+0

예 , C#에서 요청에 액세스하는 섹션을 추가 할 수 있습니까? @ 차이타야다 사리 – chandler

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 
1

: 뭔가처럼이 빈 문자열로 전송되면