簡體   English   中英

您如何解析名稱中帶有冒號的 JSON? 安卓/Java

[英]How do you parse JSON with a colon in the name? Android/Java

例如: { "primary:title":"Little Red Riding Hood"}

由於主要和標題之間的冒號,我的 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();
    }

一方面,為了回答您的問題,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;
    }

}

由於 Java 標識符不能有冒號,因此只需指定一個映射到確切 json 名稱的 json 屬性名稱,例如:

@JsonProperty("primary:title")
public String primaryTitle;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM