2014-11-11 6 views
0

HTTP 응답으로 JSON 문자열을받습니다. 내가 Newtonsoft.Json 라이브러리가JSON 문자열 직렬화 (Newtonsoft.JSON)

response: { 
    count: 524, 
    items: [{ 
     id: 318936948, 
     owner_id: 34, 
     artist: 'The Smiths', 
     title: 'How Soon Is Now', 
     duration: 233, 
     url: 'link', 
     genre_id: 9 
    }, { 
     id: 312975563, 
     owner_id: 34, 
     artist: 'Thom Yorke', 
     title: 'Guess Again!', 
     duration: 263, 
     url: 'link', 
     genre_id: 22 
    }] 
} 

, 및 클래스 응답 및 항목 :처럼이 문자열은 보이는

[JsonObject(MemberSerialization.OptIn)] 
class Response 
{ 
    [JsonProperty("count")] 
    public int count { get; set; } 
    [JsonProperty("items")] 
    public List<Item> items { get; set; } 
} 
[JsonObject(MemberSerialization.OptOut)] 
class Item 
{ 
    public string aid { get; set; } 
    public string owner_id { get; set; } 
    public string artist { get; set; } 
    public string title { get; set; } 
    public string duration { get; set; } 
    public string url { get; set; } 
    public int lyrics_id { get; set; } 
    public int album_id { get; set; } 
    public int genre_id { get; set; } 
} 

와 나는 그런 식으로 직렬화 :

Response r = JsonConvert.DeserializeObject<Response>(line); 

그것은하지 않습니다 "r"은 null로 유지됩니다. 내가 왜 틀렸어? 왜? 컴파일 중이지만 예외는 없습니다.

+1

Json을 http://jsonformatter.curiousconcept.com/에 붙여 넣을 때 "문자열을 큰 따옴표로 묶어야합니다. [코드 17, 구조 2]"와 같은 오류가 발생합니다. – dbc

+0

Json이 잘못한 것 같습니다. check here http://json2csharp.com/ – loop

+1

또한'response'는 일부 구조체의 필드/속성이지만 보이지 않습니다. – dbc

답변

0

여기에 몇 가지 문제가 있습니다

  1. 귀하의 JSON 문자열이 외부 괄호가 없습니다. 그것은 당신이 Response 클래스를 직렬화하려고하지만 필드 response이 클래스에 존재하지

    { response: { 
        count: 524, 
        items: [{ 
         id: 318936948, 
         owner_id: 34, 
         artist: 'The Smiths', 
         title: 'How Soon Is Now', 
         duration: 233, 
         url: 'link', 
         genre_id: 9 
        }, { 
         id: 312975563, 
         owner_id: 34, 
         artist: 'Thom Yorke', 
         title: 'Guess Again!', 
         duration: 263, 
         url: 'link', 
         genre_id: 22 
        }] 
    }} 
    
  2. 처럼, 그것은 분명히 일부 포함하는 클래스의 필드이다 보일 것입니다. 따라서 실제 Response을 추출해야합니다.

  3. aidItemid이어야합니다.

그래서, 다음은 작동하는 것 같다 :

  // Fix missing outer parenthesis 
      var fixedLine = "{" + line + "}"; 

      // Parse into a JObject 
      var mapping = JObject.Parse(fixedLine); 

      // Extract the "response" and deserialize it. 
      Response r = mapping["response"].ToObject<Response>(); 

      Debug.WriteLine(r.count); 
      foreach (var item in r.items) 
      { 
       Debug.WriteLine(" " + JsonConvert.SerializeObject(item)); 
      } 

이 디버그 출력을

524 
    {"id":"318936948","owner_id":"34","artist":"The Smiths","title":"How Soon Is Now","duration":"233","url":"link","lyrics_id":0,"album_id":0,"genre_id":9} 
    {"id":"312975563","owner_id":"34","artist":"Thom Yorke","title":"Guess Again!","duration":"263","url":"link","lyrics_id":0,"album_id":0,"genre_id":22} 

를 생성하고 데이터가 성공적으로 직렬화 복원 보여줍니다.

+0

그것은 그런 식으로 작동합니다, 고정 행을 사용할 수 없지만 JObject를 사용하면 역 직렬화됩니다. 그러나 나는 아직도 이해하지 못한다. 무엇이 문제인지. – Sovent

0

코드가있는 그대로 작동합니다. 받은 JSON 문자열에 처음에 response: 비트가 포함되어 있습니까? 그렇다면 문자열을 제거해야합니다 (먼저 { 문자 앞에있는 문자열을 모두 제거해야합니다). 그런 다음 효과가 있습니다.