你如何解析JSON在名称中使用冒号? Android的/ Java的 [英] How do you parse JSON with a colon in the name? Android/Java

查看:676
本文介绍了你如何解析JSON在名称中使用冒号? Android的/ Java的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如: {主:题:小红帽}

我在Java中(安卓)解析器总是被卡住,因为初级和标题之间的结肠。我可以分析什么都容易,我只需要在此帮助。

 公共类MainActivity延伸活动{
    / **第一次创建活动时调用。 * /

    TextView的txtViewParsedValue;

    私人的JSONObject的JSONObject;
    私人JSONArray jsonArray;

    的String []标题,链接,mediaDescriptions,mediaCredits,描述,dcCreators,pubDates,分类;
    的String []的永久链接,文本; // GUID
    的String [] RELS,的HREF;
    的String []的URL,媒体,高度,宽度; //媒体:内容

    字符串strParsedValue =;

    私人字符串strJSONValue;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);

        strJSONValue = readRawTextFile(这一点,R.raw.jsonextract);

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

        尝试 {
            parseJSON();

        }赶上(JSONException E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
    }

    公共无效parseJSON()抛出JSONException
    {
        txtViewParsedValue.setText(解析1);

        的JSONObject =新的JSONObject(strJSONValue);
        jsonArray = jsonObject.getJSONArray(项目);

        标题=新的String [jsonArray.length()];
        链接=新的String [jsonArray.length()];
        永久链接=新的String [jsonArray.length()];
        文本=新的String [jsonArray.length()];
        mediaDescriptions =新的String [jsonArray.length()];
        mediaCredits =新的String [jsonArray.length()];
        说明=新的String [jsonArray.length()];
        dcCreators =新的String [jsonArray.length()];
        pubDates =新的String [jsonArray.length()];
        类别=新的String [jsonArray.length()];

        txtViewParsedValue.setText(解析2);

        的for(int i = 0; I< jsonArray.length();我++)
        {
            的JSONObject对象= jsonArray.getJSONObject(我);

            标题[i] = object.getString(标题);
            链接[i] = object.getString(链接);

            JSONObject的guidObj = object.getJSONObject(GUID);
            永久链接[i] = guidObj.getString(isPermaLink);
            文[I] = guidObj.getString(文字);
            // mediaDescriptions [I] = object.getString(媒体:说明);
            // mediaCredits [I] = object.getString(媒体:信用);

                // ***解析器失败,如果注释行均按BECAUSE IMPLEMENTED
                //的:在名称之间***

            描述[I] = object.getString(说明);
            // dcCreators [I] = object.getString(DC:创造者);
            pubDates [I] = object.getString(相关的摘录);
            类别[我] = object.getString(类);
        }



        的for(int i = 0; I< jsonArray.length();我++)
        {
            strParsedValue + =\ n标题:+标题[I]
            strParsedValue + =\ nLink:+链接[I]
            strParsedValue + =\ nPermalink:+固定链接[I]
            strParsedValue + =\ n文字:+文本[I]
            strParsedValue + =\ nMedia描述:+ mediaDescriptions [I]
            strParsedValue + =\ nMedia图片来源:+ mediaCredits [I]
            strParsedValue + =\ n描述:+说明[I]
            strParsedValue + =\ NDC创造者:+ dcCreators [I]
            strParsedValue + =\ nPublication日期:+ pubDates [I]
            strParsedValue + =\ nCategory:+类[I]
            strParsedValue + =\ N的;
        }


        txtViewParsedValue.setText(strParsedValue);
    }

    公共静态字符串readRawTextFile(上下文CTX,INT渣油)
    {
         InputStream中的InputStream = ctx.getResources()openRawResource(渣油)。

            InputStreamReader的inputreader =新的InputStreamReader(InputStream的);
            的BufferedReader buffreader =新的BufferedReader(inputreader);
             串线;
             StringBuilder的文本=新的StringBuilder();

             尝试 {
               而((行= buffreader.readLine())!= NULL){
                   text.append(线);
                   //text.append('\n');
                 }
           }赶上(IOException异常E){
               返回null;
           }
             返回text.toString();
    }
 

解决方案

其一,并回答你的问题,有一个与的JSONObject和org.json没有问题。*类解析键,在他们冒号,如果他们适当地形成。下面的单元测试通过,这意味着它能够解析您的示例场景:

 公共无效testParsingKeysWithColons()抛出JSONException {
    字符串原料={\主:标题\:\小红帽\};
    JSONObject的OBJ =新的JSONObject(生);
    字符串primaryTitle = obj.getString(主:标题);
    的assertEquals(小红帽,primaryTitle);
}
 

另一个建议是使用字符串数组为您的数据是笨拙的,你会使用一个数据结构来重新present你的对象可以更好的安排。取而代之的字符串数组为标题,链接,描述;使用一个对象,它具有这些特性,使对象的列表。例如:

 公共类MyDataStructure {

    公共字符串称号;
    公共字符串primaryTitle;
    公共字符串的链接;
    公共字符串MEDIADESCRIPTION;

    公共静态类键{
        公共静态字符串title =称号;
        公共静态字符串primaryTitle =主:称号;
        公共静态字符串链接=联系;
        公共静态字符串MEDIADESCRIPTION =媒体:说明;
    }

}
 

然后你可以做所有的解析,为您和您的返回对象列表的翻译类。这是非常容易使用和跟踪。你从来没有考虑数据错开,或在你的阵列比你预期的是具有更多或更少的数据。你也有一个更容易地测试,其中的问题是,如果你输入的数据丢失任何东西,或任何你JSON的格式不正确。

 公共类MyDataStructureTranslator {

    公共静态列表< MyDataStructure> parseJson(字符串rawJsonData)抛出JSONException {

        名单< MyDataStructure>名单=新的ArrayList< MyDataStructure>();
        JSONObject的OBJ =新的JSONObject(rawJsonData);
        JSONArray ARR = obj.getJSONArray(项目);

        的for(int i = 0; I< arr.length();我++){
            的JSONObject电流= arr.getJSONObject(ⅰ);
            MyDataStructure项目=新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(项目);
        }

        返回列表;
    }

}
 

For example: { "primary:title":"Little Red Riding Hood"}

My Parser in Java (Android) is always getting stuck because of the colon between primary and title. I can parse anything else with ease, I just need help in this.

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();
    }

解决方案

For one, and to answer your question, there is no issue with JSONObject and the org.json.* classes parsing keys with colons in them if they're properly formed. The following unit test passed which means it was able to parse your example scenario:

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);
}

Another suggestion is that using arrays of Strings for your data is clumsy and you'd be much better organized using a data structure to represent your objects. Instead of string arrays for titles, links, descriptions; use an object that has these properties and make a list of the objects. For example:

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";
    }

}

And then you can make a "translator" class that does all the parsing for you and returns a list of your object. This is much easier to work with and keep track of. You never have to think about data misaligning or having more or less data in one of your arrays than you expected. You also have a much easier time testing where the problem is if your input data is missing anything or any of your json is malformed.

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;
    }

}

这篇关于你如何解析JSON在名称中使用冒号? Android的/ Java的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆