2015-02-06 2 views
0

제발 도와주세요, C# 및 JSON으로 작업하고 있습니다. newtonsoft 네임 스페이스를 사용하여 C#에서 json 데이터를 deserialize하려고합니다.배열을 비 직렬화 json C#

class lastResponse 
{ 
    public string type { get; set; } 
    public Metadata metadata { get; set; } 
    // public string[] course { get; set; } 
    public List<object> course { get; set; } 
    public string publisher { get; set; } 
} 

public class Metadata 
{ 
    public string bookID { get; set; } 
    public string title { get; set; } 
    public string filename { get; set; } 
} 

이 코드 :

var errorMsg = JsonConvert.DeserializeObject<lastResponse>(downloader.LastResponse); 

날이 오류를 제공합니다 :

"An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'BookManager.lastResponse' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly." 

날 내가 여기에 누락 알아낼 제발 도와주세요 여기

내 클래스입니다.

+0

그것이 * 완전한 * 오류라고는 생각되지 않습니다. 이것이 예외 인 경우 전체 스택 추적을 게시하십시오. 이것이 컴파일 타임 오류라면 전체 오류를 게시하십시오. –

+0

이 '문자열'을 'downloader.LastResponse' 표시 할 수 있습니까 –

+0

@JonSkeet이 오류가 발생했습니다. "Newtonsoft.Json.JsonSerializationException'유형의 처리되지 않은 예외가 Newtonsoft.Json.dll에서 발생했습니다. 추가 정보 : Can not 형식에 JSON 객체 (예 : { "name": "value"})가 필요하기 때문에 현재 JSON 배열 (예 : [1,2,3])을 유형 'BookManager.lastResponse'로 역 직렬화합니다. – Red

답변

0

가장 큰 이유는 downloader.LastResponse에서 가져 오는 json이 배열이 아닐 수 있습니다.

귀하의 Json은 이와 같을 수 있습니다. 변경할 필요가있는 무엇

{ 
    "type": "First", 
    "metadata": { 
     "bookID": "book123", 
     "title": "bookTitle Here", 
     "filename": "book file name" 
    }, 
    "course": [ 
     { 
      "1": "01", 
      "2": "02" 
     }, 
     { 
      "001": "001", 
      "002": "002" 
     } 
    ], 
    "publisher": "you" 
} 

downloader.LastResponse에서 JSON 배열을 전달하거나 다음과 같이 당신이 당신의 직렬화 객체 문을 변경할 수 있습니다입니다.

JsonConvert.DeserializeObject<lastResponse>(downloader.LastResponse); 

정확한 JSON은 다음과 같습니다.

public class YouCustomClassConverter : JavaScriptConverter 
{ 
    public override object Deserialize(IDictionary<string, object> dictionary, Type type,      JavaScriptSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 

    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) 
    { 
     throw new NotImplementedException(); 
    } 

    //and first you need register type, which you want Deserialize 
    public override IEnumerable<Type> SupportedTypes 
    { 
     get { return new[] { typeof(YouCustomClass) }; } 
    } 

} 

//and then example of using JavaScriptSerializer with custom converter 
var ser = new JavaScriptSerializer(); 
ser.RegisterConverters(new JavaScriptConverter[] { new YouCustomClassConverter() }); 
try 
{ 
    YouCustomClass obj = ser.Deserialize(jsonString); 
} 

참고 :

**[** 
    { 
     "type": "First", 
     "metadata": { 
      "bookID": "book123", 
      "title": "bookTitle Here", 
      "filename": "book file name" 
     }, 
     "course": [ 
      { 
       "1": "01", 
       "2": "02" 
      }, 
      { 
       "001": "001", 
       "002": "002" 
      } 
     ], 
     "publisher": "you" 
    } 
**]** 

이이 같은 CustomJsonConverter을 사용할 수 있습니다, 당신은 또한 javascriptserializer

string s = "YouJsonText"; 
var serializer = new JavaScriptSerializer(); 
var result = serializer.Deserialize(s); 
//or 
YouCustomClass res = serializer.Deserialize<YouCustomClass>(sb.ToString()); 

을 사용할 수 있습니다 문제 :

+0

deserialise 문을 변경하려고했지만 Newtonsoft.Json.dll에서 'Newtonsoft.Json.JsonSerializationException'유형의 처리되지 않은 예외가 발생했습니다. 추가 정보 : 현재 JSON 배열 (예 : [1,2,3])을 'BookManager'유형으로 역 직렬화 할 수 없습니다. JSON 객체 (예 : { "name": "value"})가 올바르게 역 직렬화되어야하므로 JSON 객체가 필요하기 때문에 lastResponse를 호출해야합니다. ""마지막 응답은 첫 번째 블록에있는 예제와 같습니다. – Red

+0

@SthokoManqele 당신은 당신의 json을 공유 할 수 있습니까? –

+0

{ "유형", "메타 데이터"를 "예약": { "bookID로서": "책 000f6b3e-f616-4417-b1b8-66f375e3e4b4", "제목": "대화 형 자산 시험 도서", " 파일 이름 ":"대화 형 데모 ", }, "물론 "[ "301 Lieb 데모 " , "발행인 ":"ITS ", } – Red

0

를 해결할 수있는 당신이 사용을 필요로 using System.Web.Script.Serialization;