2011-11-06 66 views
0

這裏嵌套JSON是我想要做的事:試圖解析使用GSON

public static final String json = "[{'quotes':[{'quote':'sdfsdfsdfdsf!','source':'sdfsdfsdfsdfsdf'},{'quote':'sdfsdfsdfsdf!','source':'-sdfsfsdf'},{'quote':'Isdfsf','source':'sfsfsf'}]}]"; 

Gson gson = new Gson(); 
     JsonParser parser = new JsonParser(); 
     JsonArray array = parser.parse(json).getAsJsonArray(); 

     Event event = gson.fromJson(array.get(0), Event.class); 


     System.out.println("Using Gson.fromJson() to get:" + event.getQuotes()); 

這裏是事件類:

static class Event { 
     private JsonArray quotes; 
     private Event(JsonArray quotes) { 
     this.quotes = quotes; 

     } 
     public JsonArray getQuotes() { 
      return quotes; 
     } 
     public void setQuotes(JsonArray quotes) { 
      this.quotes = quotes; 
     } 

     } 

從本質上講,我想解析出內容。抓住「引號」並將內容放入另一個JsonArray中,而不是它?然而,該應用程序崩潰,因爲我不認爲它這樣工作。

任何想法?我一直在拉我的頭髮。

+0

它是否可以使用本地JSON類做什麼?請讓我知道,所以我建議一個解決方案。 –

+0

你能告訴我們你的錯誤嗎? logcat說什麼? –

回答

1

你的JSON字符串無效,只檢查在這裏:http://jsonlint.com/

那麼你所有的JSON字符串首先應該是這樣的:

[{"quotes":[{"quote":"sdfsdfsdfdsf!","source":"sdfsdfsdfsdfsdf"}, 
{"quote":"sdfsdfsdfsdf!","source":"-sdfsfsdf"},{"quote":"asdfsf","source":"sfsfsf"}]}] 

如果你想在字符串變量來存儲則:

JSON解析使用本地類(未使用GSON或任何API):

JsonObject obj = new JsonObject(json); 
JsonArray array = obj.getJsonArray("quotes"); 

for(int i=0; i<array.length; i++) 
{ 
    JsonObject subObj = array.getJsonObject(i); 
    String strQuotes = subObj.getString("quote"); 
    String strSource = subObj.getString("source"); 
} 
0

我試圖解析出的內容。抓住「引號」,並將內容放入另一個JsonArray

我會採取不同的方法來處理這個數據結構,

由於使用GSON是可能的,然後用它爲它的擅長,而忘記了處理像JsonArray和JSON JSONObject的API組件。 Gson非常適合將JSON數據簡單地綁定到Java數據結構。因此,我可能會採取類似於以下的方法,然後允許對沒有JSON問題的Java數據結構進行簡單操作。

輸入JSON

[ 
    { 
     "quotes": [ 
      { 
       "quote": "I never think of the future. It comes soon enough.", 
       "source": "Albert Einstein" 
      }, 
      { 
       "quote": "A riot is the language of the unheard.", 
       "source": "Martin Luther King, Jr." 
      }, 
      { 
       "quote": "A hero is someone who understands the responsibility that comes with his freedom.", 
       "source": "Bob Dylan" 
      } 
     ] 
    } 
] 

Java代碼的

import java.io.FileReader; 

import com.google.gson.Gson; 

public class GsonFoo 
{ 
    public static void main(String[] args) throws Exception 
    { 
    Gson gson = new Gson(); 
    Event[] events = gson.fromJson(new FileReader("input.json"), Event[].class); 
    System.out.println(events[0].quotes[0].quote); 
    System.out.println(events[0].quotes[0].source); 
    } 
} 

class Event 
{ 
    Quote[] quotes; 
} 

class Quote 
{ 
    String quote; 
    String source; 
}