2017-01-25 4 views
1

json.NET 배열을 C# 목록으로 역 직렬화하려고하는 문제가있는 것 같습니다 (Json.NET을 사용하고 있습니다). 문제는 내가 오류를 받고 있어요된다json을 C# 목록 개체로 비 직렬화하는 방법

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'ProjectName.WebServices.EventWebMethods+ServiceItem' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. Path '[0]', line 1, position 2.

이 그것에 JSON.stringify를 자바 스크립트 배열을 복용하고 사용하여 만든 내 JSON 코드 :

[["6249","Locked"],["6250","Locked"],["6251","Locked"]] 

이것은 C# 코드는 나는 이것을 사용하고있다 :

[Serializable] 
    public class ServiceItem 
    { 
     long lngId{ get; set; } 
     string strStatus{ get; set; } 

     public ServiceItem() { } 
    } 

    [WebMethod(EnableSession = true)] 
    public string Create(string strJSON) 
    { 
     //Error happens on this next line: 
     List<ServiceItem> ServiceData = JsonConvert.DeserializeObject<List<ServiceItem>>(strJSON); 
     return "test"; 
    } 

어떻게 이것을 C# 클래스로 직렬화 해제 할 수 있을까? 어떤 도움을 주셔서 감사합니다! 제안에 따라이 변수 이름을 포함하도록

UPDATE는 내 자바 스크립트로 변경했습니다. 여전히 같은 오류.

[ 
[\"lngId\" : \"6249\",\"strStatus\" : \"Locked\"], 
[\"lngId\" : \"6250\",\"strStatus\" : \"Locked\"], 
[\"lngId\" : \"6251\",\"strStatus\" : \"Locked\"] 
] 

가 문제가있는 경우, 그리고, 왜 JSON.Stringify 그렇게 중요하지 않습니다 중괄호 위치 : 다음은 C#을 변수에 JSON은 무엇입니까? 2

UPDATE는 그것을 알아 냈다. 다음과 같이 각 json 항목을 만들어야합니다.

arrServices.push({"lngId": intServiceID, "strStatus" : "Locked"}); 

이제는 작동합니다. 도와 주셔서 감사합니다!

+0

json은 (는) 유효한 친구가 아닙니다. http://json2csharp.com/ – saj

답변

4

예 JSON은 문자열 배열의 배열을 나타냅니다. 당신의 ServiceItem 클래스에 의해 표현 스키마를 나타내는 JSON은 다음과 같이 보일 것이다 :

[ 
    { 
     "lngID":"6249", 
     "strStatus":"Locked" 
    }, 
    { 
     "lngID":"6250", 
     "strStatus":"Locked" 
    }, 
    { 
     "lngID":"6251", 
     "strStatus":"Locked" 
    } 
] 

당신은 (그것이 당신의 클래스를 일치하도록) 다르게 다른 쪽 끝에서 데이터를 직렬화 할 필요가있다.

List<ServiceItem> ServiceData = 
    JArray 
    .Parse(input) 
    .Select(x => x.ToArray()) 
    .Select(x => new ServiceItem() 
     { 
      lngId = x[0].Value<int>(), 
      strStatus = x[1].Value<String>() 
     }) 
    .ToList(); 

또는 사용자 정의 JsonConverter을 구현 : 그 옵션이 아닌 경우 수동으로 서버에 JSON을 역 직렬화해야 할 것입니다.

+0

고맙습니다. 나는 그것을 작동하게했다! 관심있는 사람은 원래 질문의 "업데이트 2"를 참조하십시오. – Vandel212

관련 문제