2013-08-24 6 views
1
사용

메신저 다음 JSON 파일을 읽으려고 : 내가 가정 있도록 "항목"개체에 무엇이 아는IllegalStateException이 GSON

public class RSSWrapper{ 
    public RSS rss; 

    public class RSS{ 
     public Channel channel; 
    } 

    public class Channel{ 
     public List<Item> item; 

    } 
    public class Item{ 
     String description;//Main Content 
     String dc_identifier;//Link 
     String pubDate; 
     String title; 

    } 
} 

임에만 관심이 객체에

{ "rss" : { 
    "@attributes" : {"version" : "2.0" }, 
     "channel" : { 
      "description" : "Channel Description", 
      "image" : { 
       "link" : "imglink", 
       "title" : "imgtitle", 
       "url" : "imgurl" 
      }, 

      "item" : { 
       "dc_format" : "text", 
       "dc_identifier" : "link", 
       "dc_language" : "en-gb", 
       "description" : "Description Here", 
       "guid" : "link2", 
       "link" : "link3", 
       "pubDate" : "today", 
       "title" : "Title Here" 
      }, 

      "link" : "channel link", 
      "title" : "channel title" 
     } 
    } 
} 

Gson gson = new Gson(); 
RSSWrapper wrapper = gson.fromJson(JSON_STRING, RSSWrapper.class); 

를하지만, 메신저 오류가 점점 : 호출 할 때 위의 클래스는 일하는 것이

나는 이것이 의미하는 바를 알지 못하므로 어디서 오류를 찾을 지 모르겠다. GSON에 대한 더 나은 지식을 가진 누군가 나를 도울 수 있을까?

감사합니다 :)

답변

1

당신이 JSON 입력과 같은 방법을 제어하는 ​​경우, 당신은 당신이 당신의 프로그램이 item 배열 또는 객체를 모두 처리 할 수 ​​싶지 및 않으면 JSON 배열

"item" : [{ 
    "dc_format" : "text", 
    "dc_identifier" : "link", 
    "dc_language" : "en-gb", 
    "description" : "Description Here", 
    "guid" : "link2", 
    "link" : "link3", 
    "pubDate" : "today", 
    "title" : "Title Here" 
}] 

item을 변경하는 것이 더 낫다 동일한 RSSWrapper 클래스로; 여기에 프로그래밍 방식의 솔루션이 있습니다. 자바 org.json 파서를 사용

JSONObject jsonRoot = new JSONObject(JSON_STRING); 
JSONObject channel = jsonRoot.getJSONObject("rss").getJSONObject("channel"); 

System.out.println(channel); 
if (channel.optJSONArray("item") == null) { 
    channel.put("item", new JSONArray().put(channel.getJSONObject("item"))); 
    System.out.println(channel); 
} 

Gson gson = new Gson(); 
RSSWrapper wrapper = gson.fromJson(jsonRoot.toString(), RSSWrapper.class); 

System.out.println(wrapper.rss.channel.item.get(0).title); // Title Here 

코드는 단순히 배열로 포장하여 JSONObject을 대체합니다. item이 이미 JSONArray 인 경우에는 JSON_STRING이 그대로 유지됩니다.

1

귀하의 JSON 문자열과 RSSWrapper 클래스는 호환되지 같습니다 JSON 문자열이 하나 개의 항목을 포함하면서 ChannelList<Item>을 가지고 기대하고있다. 당신은 Channel 수정 중 하나가 :

public class Channel{ 
    public Item item; 

} 

을하거나 JSON과 같은 :

"item" : [{ 
    "dc_format" : "text", 
    "dc_identifier" : "link", 
    "dc_language" : "en-gb", 
    "description" : "Description Here", 
    "guid" : "link2", 
    "link" : "link3", 
    "pubDate" : "today", 
    "title" : "Title Here" 
}], 

가 하나 개의 요소 배열임을 나타냅니다.

+0

대개 두 개 이상의 항목이 있습니다.이 경우에는 하나만 있습니다. – Edd

+0

@clairharrison 제 대답의 두 번째 부분을 봅니다. – Katona