2012-11-19 52 views
2

例如:{ "primary:title":"Little Red Riding Hood"}如何用名稱中的冒號解析JSON? Android/Java

Java中的我的解析器(Android)由於主和標題之間的冒號而一直卡住。我可以輕鬆解析其他任何東西,我只需要幫助。

public class MainActivity extends Activity { 
    /** Called when the activity is first created. */ 

    TextView txtViewParsedValue; 

    private JSONObject jsonObject; 
    private JSONArray jsonArray; 

    String [] titles, links, mediaDescriptions, mediaCredits, descriptions, dcCreators, pubDates, categories; 
    String [] permalinks, texts;   // guid 
    String [] rels, hrefs; 
    String [] urls, media, heights, widths; // media:content 

    String strParsedValue = ""; 

    private String strJSONValue; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     strJSONValue = readRawTextFile(this, R.raw.jsonextract); 

     txtViewParsedValue = (TextView) findViewById(R.id.text_view_1); 

     try { 
      parseJSON(); 

     } catch (JSONException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    public void parseJSON() throws JSONException 
    { 
     txtViewParsedValue.setText("Parse 1"); 

     jsonObject = new JSONObject(strJSONValue); 
     jsonArray = jsonObject.getJSONArray("item"); 

     titles = new String[jsonArray.length()]; 
     links = new String[jsonArray.length()]; 
     permalinks = new String[jsonArray.length()]; 
     texts = new String[jsonArray.length()]; 
     mediaDescriptions = new String[jsonArray.length()]; 
     mediaCredits = new String[jsonArray.length()]; 
     descriptions = new String[jsonArray.length()]; 
     dcCreators = new String[jsonArray.length()]; 
     pubDates = new String[jsonArray.length()]; 
     categories = new String[jsonArray.length()]; 

     txtViewParsedValue.setText("Parse 2"); 

     for (int i=0; i<jsonArray.length(); i++) 
     { 
      JSONObject object = jsonArray.getJSONObject(i); 

      titles[i] = object.getString("title"); 
      links[i] = object.getString("link"); 

      JSONObject guidObj = object.getJSONObject("guid"); 
      permalinks[i] = guidObj.getString("isPermaLink"); 
      texts[i] = guidObj.getString("text"); 
      //mediaDescriptions[i] = object.getString("media:description"); 
      //mediaCredits[i] = object.getString("media:credit"); 

       // *** THE PARSER FAILS IF THE COMMENTED LINES ARE IMPLEMENTED BECAUSE 
       // OF THE : IN BETWEEN THE NAMES *** 

      descriptions[i] = object.getString("description"); 
      //dcCreators[i] = object.getString("dc:creator"); 
      pubDates[i] = object.getString("pubDate"); 
      categories[i] = object.getString("category"); 
     } 



     for (int i=0; i<jsonArray.length(); i++) 
     { 
      strParsedValue += "\nTitle: " + titles[i]; 
      strParsedValue += "\nLink: " + links[i]; 
      strParsedValue += "\nPermalink: " + permalinks[i]; 
      strParsedValue += "\nText: " + texts[i]; 
      strParsedValue += "\nMedia Description: " + mediaDescriptions[i]; 
      strParsedValue += "\nMedia Credit: " + mediaCredits[i]; 
      strParsedValue += "\nDescription: " + descriptions[i]; 
      strParsedValue += "\nDC Creator: " + dcCreators[i]; 
      strParsedValue += "\nPublication Date: " + pubDates[i]; 
      strParsedValue += "\nCategory: " + categories[i]; 
      strParsedValue += "\n"; 
     } 


     txtViewParsedValue.setText(strParsedValue); 
    } 

    public static String readRawTextFile(Context ctx, int resId) 
    { 
     InputStream inputStream = ctx.getResources().openRawResource(resId); 

      InputStreamReader inputreader = new InputStreamReader(inputStream); 
      BufferedReader buffreader = new BufferedReader(inputreader); 
      String line; 
      StringBuilder text = new StringBuilder(); 

      try { 
       while ((line = buffreader.readLine()) != null) { 
        text.append(line); 
        //text.append('\n'); 
       } 
      } catch (IOException e) { 
       return null; 
      } 
      return text.toString(); 
    } 
+4

你正在使用哪個解析器?如果它無法處理,那就錯誤了:使用另一個解析器。 –

+0

你如何解析它?你需要給我們一些工作。 – climbage

+0

@JBNizet似乎他正在試圖建立自己的... – climbage

回答

2

原因之一,並回答你的問題,有一個與的JSONObject和org.json沒有問題。*解析與他們冒號鍵類,如果它們正常形成。下面的單元測試通過,這意味着它能夠解析您的示例場景:

public void testParsingKeysWithColons() throws JSONException { 
    String raw = "{ \"primary:title\":\"Little Red Riding Hood\"}"; 
    JSONObject obj = new JSONObject(raw); 
    String primaryTitle = obj.getString("primary:title"); 
    assertEquals("Little Red Riding Hood", primaryTitle); 
} 

另一個建議是使用字符串數組爲你的數據是笨拙的和你使用的數據結構來代表組織要好得多你的對象。而不是標題,鏈接,描述的字符串數組;使用具有這些屬性的對象並製作對象列表。例如:

public class MyDataStructure { 

    public String title; 
    public String primaryTitle; 
    public String link; 
    public String mediaDescription; 

    public static class Keys { 
     public static String title = "title"; 
     public static String primaryTitle = "primary:title"; 
     public static String link = "link"; 
     public static String mediaDescription = "media:description"; 
    } 

} 

然後你就可以做一個「翻譯」的類,它所有的解析,爲您和您的返回對象的列表。這很容易處理和跟蹤。您從來不需要考慮數據錯位,或者數組中的數據多於或少於您預期的數組。如果你的輸入數據丟失了任何東西或者你的任何json格式錯誤,你也可以更容易地測試問題所在。

public class MyDataStructureTranslator { 

    public static List<MyDataStructure> parseJson(String rawJsonData) throws JSONException { 

     List<MyDataStructure> list = new ArrayList<MyDataStructure>(); 
     JSONObject obj = new JSONObject(rawJsonData); 
     JSONArray arr = obj.getJSONArray("item"); 

     for(int i = 0; i < arr.length(); i++) { 
      JSONObject current = arr.getJSONObject(i); 
      MyDataStructure item = new MyDataStructure(); 
      item.title = current.getString(MyDataStructure.Keys.title); 
      item.primaryTitle = current.getString(MyDataStructure.Keys.primaryTitle); 
      item.link = current.getString(MyDataStructure.Keys.link); 
      item.mediaDescription = current.getString(MyDataStructure.Keys.mediaDescription); 
      list.add(item); 
     } 

     return list; 
    } 

} 
+0

只是爲了告訴你,我現在正在閱讀你的答案。我會嘗試一下 – user1028408