解析复杂的JSON响应

时间:2013-05-12 09:59:52

标签: java android json

我编写了一个json解析器类来解析从http请求返回的简单json数组。如何修改下面的代码以从对象"条目"中获取数据?来自网址 Request URL

try {
            JSONArray jArray = new JSONArray(result);
            JSONObject json_data = null;
                for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                String title = json_data.getString("title");
                String link=json_data.getString("link");
                HashMap<String, String>map=new HashMap<String, String>();
                map.put("title",title);
                map.put("link",link);
                jlist.add(map);
            }

响应:

{
    "responseData": {
        "feed": {
            "feedUrl": "http://ramrojob.com/feed",
            "title": "Ramro Job",
            "link": "http://ramrojob.com",
            "author": "",
            "description": "...your pathway to success",
            "type": "rss20",
            "entries": [
                {
                    "title": "Monitoring and Evaluation Specialist Wanted at GRM International",
                    "link": "http://ramrojob.com/job/2013/05/12/monitoring-and-evaluation-specialist-wanted-at-grm-international.html",
                    "author": "Bandana Aryal",
                    "publishedDate": "Sun, 12 May 2013 01:10:24 -0700",
                    "contentSnippet": "Key Responsibilities Under direction of the Team Leader, responsible for the design and roll out of programme M&#38;E plan, ...",
                    "content": "<p><strong>Key Responsibilities</strong></p>\n<ul>\n<li>Under direction of the Team Leader, responsible for the design and roll out of programme M&amp;E plan, including design of the logframe and key performance indicators.</li>\n<li>Track programme progress against indicators and ensure early identification of any areas requiring remedial action.</li>\n<li>Carry out site visits and provide M&amp;E support and training for local partners.</li>\n<li>Harmonise programme monitoring indicators and systems with national M&amp;E systems.</li>\n<li>Promote use of data to inform decision making and link evidence-based approaches to achievement of results.</li>\n<li>Support operations research and specialised studies, such as client satisfaction, cost-effectiveness, and impact evaluation.</li>\n<li>Solicit and manage local data collection and research teams, as needed.</li>\n<li>Contribute to the preparation of regular progress reports, technical deliverables, presentations, and annual work plans.</li>\n</ul>\n<p><strong>Qualifications</strong></p>\n<ul>\n<li>Seven or more years of experience monitoring and evaluating reproductive health and family planning programmes, including promoting use of data for decision-making.</li>\n<li>Strong technical grasp of relevant health issues: sexual and reproductive health; family planning; maternal, new-born, and child health; HIV and AIDS; and health equity.</li>\n<li>Understanding of health market dynamics and the health system in Nepal.</li>\n<li>Demonstrated experience working with government, private sector, and nongovernmental health sector partners in Nepal, at national and decentralised levels.</li>\n<li>Experience supporting DFID, European Union, USAID, World Bank, or other donor-funded or government health programmes.</li>\n<li>Strong quantitative and qualitative research and analysis skills.</li>\n<li>Demonstrated experience with computerised management information systems, databases, MS Office, and other relevant skills.</li>\n<li>Ability to graphically present data in ways that engage and influence target audiences.</li>\n<li>Knowledge of in-country and international guidelines pertaining to research ethics.</li>\n<li>Strong personal qualities, including integrity, commitment to excellence, equality, openness, inclusiveness, and collegiality.</li>\n<li>Excellent written and spoken English required, local languages are a distinct advantage.</li>\n<li>Advanced degree/s in relevant discipline preferred.</li>\n<li>Nepali nationals strongly encouraged to apply.</li>\n</ul>\n<p>The post <a href=\"http://ramrojob.com/job/2013/05/12/monitoring-and-evaluation-specialist-wanted-at-grm-international.html\">Monitoring and Evaluation Specialist Wanted at GRM International</a> appeared first on <a href=\"http://ramrojob.com\">Ramro Job</a>.</p>",
                    "categories": [
                        "Uncategorized"
                    ]
                },
                {
                    "title": "Director of Finance and Admin Wanted at Abt Associates",
                    "link": "http://ramrojob.com/job/2013/05/12/director-of-finance-and-admin-wanted-at-abt-associates.html",
                    "author": "Bandana Aryal",
                    "publishedDate": "Sun, 12 May 2013 01:02:28 -0700",
                    "contentSnippet": "Job Responsibilities: Abt Associates seeks a Director of Finance and Administration for an upcoming DFID-funded family planning ...",
                    "content": "<p><strong>Job Responsibilities:</strong></p>\n<p>Abt Associates seeks a Director of Finance and Administration for an upcoming DFID-funded family planning program in Nepal. The initiative will work with the Ministry of Health and Population to increase use of modern high-quality family planning methods by the most vulnerable and excluded women by supply innovative and high quality family planning services. The program will also work with the Ministry of Health and Population to ensure better choices and availabilites of reproductive health commodities.</p>\n<p>The Director of Finance and Administration will be responsible for the management of the contract, procurement, subcontracting, financial management and reporting, and general administrative support of the program. S/he will develop and track budgets, manage payroll and vendor relations, and control all financial transactions and reporting, both for the client and for Abt Associates headquarters.</p>\n<p>Specific responsibilities will include:</p>\n<ul>\n<li>Ensure compliance with terms and references in the contract;</li>\n<li>Develop and implement financial and administrative policies and procedures that meet project requirements and donor regulations;</li>\n<li>Create and maintain financial reporting and tracking systems, and provide financial performance updates on project activities;</li>\n<li>Prepare budgets and revenue plans for project programming and corporate reporting;</li>\n<li>Oversee financial and HR administration of project (purchase requisitions, consulting agreements, vendor invoices, client invoices, payroll etc.);</li>\n<li>Manage vendors and subcontractors in compliance with Abt and DfID policies and regulations;</li>\n<li>Supervise all financial and administrative staff;</li>\n<li>Provide training to field staff on project procedures as well as building skill-levels of project staff in the area of finance, administration, and project management.</li>\n</ul>\n<p><strong>Skills Prerequisites:</strong></p>\n<ul>\n<li>Bachelor’s Degree (minimum) or master’s degree (preferred) in Business, Finance, Accounting or other relevant field;</li>\n<li>10 years of experience in administration, project management and/or financial management;</li>\n<li>5 years of experience working with international donors in a development setting;</li>\n<li>Experience with DfID contracts desirable;</li>\n<li>Strong analytical and computer skills, with emphasis on budgeting and financial analysis;</li>\n<li>Excellent inter-personal, communication and organizational skills;</li>\n<li>Capabilities in Nepali or other South Asian languages are desirable.</li>\n</ul>\n<p>The post <a href=\"http://ramrojob.com/job/2013/05/12/director-of-finance-and-admin-wanted-at-abt-associates.html\">Director of Finance and Admin Wanted at Abt Associates</a> appeared first on <a href=\"http://ramrojob.com\">Ramro Job</a>.</p>",
                    "categories": [
                        "Uncategorized"
                    ]
                },
                {
                    "title": "Technical Director Wanted at Family Planning Nepal",
                    "link": "http://ramrojob.com/job/2013/05/12/technical-director-wanted-at-family-planning-nepal.html",
                    "author": "Bandana Aryal",
                    "publishedDate": "Sun, 12 May 2013 00:57:03 -0700",
                    "contentSnippet": "Skills Prerequisites: Masters Degree (minimum) in Public Health, Business Administration or related relevant discipline Ten ...",
                    "content": "<p><strong>Skills Prerequisites:</strong></p>\n<ul>\n<li>Masters Degree (minimum) in Public Health, Business Administration or related relevant discipline</li>\n<li>Ten years (10) of relevant professional experience, including sales or marketing, and strong business acumen in areas of business process and analysis would be highly valued</li>\n<li>Eight (8) years experience working in health sector projects or initiatives involving multiple stakeholder groups, including NGOs and the private health sector</li>\n<li>Successful prior experience in social marketing or franchising</li>\n<li>Proven track record of building and sustaining effective partnerships, advocating effectively and communicating to various constituencies</li>\n<li>Ability to coordinate in a dynamic environment</li>\n<li>Substantial experience in building capacity in the non-state/private sector</li>\n<li>Ability to independently plan and execute complex tasks while addressing daily management details and remaining organized and focused on long-term deadlines and strategies</li>\n<li>Solid professional reputation and strong, demonstrated interpersonal skills</li>\n<li>Professional working experience in Nepal desirable</li>\n<li>Fluency in Nepali desirable</li>\n<li>Excellent written and oral presentation skills in English</li>\n</ul>\n<p>The post <a href=\"http://ramrojob.com/job/2013/05/12/technical-director-wanted-at-family-planning-nepal.html\">Technical Director Wanted at Family Planning Nepal</a> appeared first on <a href=\"http://ramrojob.com\">Ramro Job</a>.</p>",
                    "categories": [
                        "Uncategorized"
                    ]
                },
                {
                    "title": "Monitoring and Evaluation Analyst Wanted at UN Women",
                    "link": "http://ramrojob.com/job/2013/05/12/monitoring-and-evaluation-analyst-wanted-at-un-women.html",
                    "author": "Bandana Aryal",
                    "publishedDate": "Sun, 12 May 2013 00:46:37 -0700",
                    "contentSnippet": "Core Competencies Knowledge of current practices in the area of monitoring and evaluation, knowledge management Promotes the ...",
                    "content": "<p><b>Core Competencies</b></p>\n<ul>\n<li>Knowledge of current practices in the area of monitoring and evaluation, knowledge management</li>\n<li>Promotes the vision, mission, and strategic goals of UN Women;</li>\n<li>Displays cultural, gender, religion, race, nationality and age sensitivity and adaptability</li>\n<li>Fostering innovation and empowerment</li>\n<li>Working in teams at all levels</li>\n<li>Communicating information and ideas/knowledge sharing</li>\n<li>Analytical and strategic thinking/results orientation/commitment to Excellence</li>\n</ul>\n<p><span style=\"text-decoration:underline\"><strong>Qualifications and Experience:</strong></span></p>\n<ul>\n<li>Master’s Degree in Economics, Management, Rural Development, Social Sciences, or related field. Additional certification in statistics, MIS management and Monitoring and Evaluation will be considered as an asset.</li>\n<li>Two years of relevant professional experience in the field of rights based monitoring and evaluation;</li>\n<li>Experience in the management of gender equality and women’s empowerment programmes or analytic work in gender and development, gender analysis and/or human rights;</li>\n<li> Good knowledge of rights-based approach and result-based management.</li>\n<li> Experience related to UN Women’s mandate and activities would be an added advantage;</li>\n<li> Sound knowledge of international standards on human rights, women’s rights and related instruments;</li>\n<li>A proven ability to liaise with a myriad of stakeholders and partners, including government, civil society, international organizations and grassroots organizations</li>\n</ul>\n<p>The post <a href=\"http://ramrojob.com/job/2013/05/12/monitoring-and-evaluation-analyst-wanted-at-un-women.html\">Monitoring and Evaluation Analyst Wanted at UN Women</a> appeared first on <a href=\"http://ramrojob.com\">Ramro Job</a>.</p>",
                    "categories": [
                        "The Himalayan Times"
                    ]
                }
            ]
        }
    },
    "responseDetails": null,
    "responseStatus": 200
}

这也没有...或者我错过了什么?

 try {
                JSONObject obj = new JSONObject(result);
                JSONObject responseJson=obj.getJSONObject("responseData");
                JSONObject feedjson=responseJson.getJSONObject("feed");
                JSONArray entriesJSON=feedjson.getJSONArray("entries");
                JSONObject json_data = null;
                Log.d("parseJson","sad");
                for (int i = 0; i < entriesJSON.length(); i++) {
                    json_data = entriesJSON.getJSONObject(i);
                    String title=json_data.getString("title");
                    String link=json_data.getString("link");
                    HashMap<String, String>map=new HashMap<String, String>();
                    map.put("title",title);
                    map.put("link", link);
                    jlist.add(map);
                }
            }

我的Logcat日志:

05-13 15:50:27.963: W/dalvikvm(12494): threadid=11: thread exiting with uncaught exception (group=0x410a42a0)
05-13 15:50:28.033: E/AndroidRuntime(12494): FATAL EXCEPTION: AsyncTask #1
05-13 15:50:28.033: E/AndroidRuntime(12494): java.lang.RuntimeException: An error occured while executing doInBackground()
05-13 15:50:28.033: E/AndroidRuntime(12494):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.lang.Thread.run(Thread.java:856)
05-13 15:50:28.033: E/AndroidRuntime(12494): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-13 15:50:28.033: E/AndroidRuntime(12494):    at android.os.Handler.<init>(Handler.java:121)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at android.widget.Toast$TN.<init>(Toast.java:361)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at android.widget.Toast.<init>(Toast.java:97)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at android.widget.Toast.makeText(Toast.java:254)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at np.com.smarttech.jobslist.MainActivity.parseJson(MainActivity.java:157)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at np.com.smarttech.jobslist.MainActivity.access$0(MainActivity.java:104)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at np.com.smarttech.jobslist.MainActivity$JobThread.doInBackground(MainActivity.java:77)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at np.com.smarttech.jobslist.MainActivity$JobThread.doInBackground(MainActivity.java:1)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-13 15:50:28.033: E/AndroidRuntime(12494):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
05-13 15:50:28.033: E/AndroidRuntime(12494):    ... 5 more

1 个答案:

答案 0 :(得分:4)

根据您对上述网址的回复,您应该像这样解析

JSONObject obj=new JSONObject(jsonString);

JSONObject responseJson=obj.getJSONObject("responseData");
JSONObject feedjson=responseJson.getJSONObject("feed");
JSONArray entriesJSON=feedjson.getJSONArray("entries");
 for (int i = 0; i < entriesJSON.length(); i++) {
  ...
   ..
 }

修改

新的异常发生是因为您尝试从后台线程显示 Toast 。使用处理程序对象将 Toast 发送到 MainThread

有关线程和UI的更多信息,请查看此处:Android Background Threads