如何用名称中的冒号解析JSON?安卓/ Java的

时间:2012-11-19 20:56:43

标签: java android json parsing

例如:{ "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();
    }

2 个答案:

答案 0 :(得分: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;
    }

}

答案 1 :(得分:0)

由于Java标识符不能包含冒号,因此只需指定一个json属性名称即可,该名称映射到确切的json名称,例如:

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