小编典典

JSON解析为Java-Android应用程序

json

我需要在Java Android Appl中解析json字符串的帮助。

JSON文件的文本:

{"data":{"columns":["location_id","name","description","latitude","longitude","error","type","type_id","icon_media_id","item_qty","hidden","force_view"],"rows":[[2,"Editor","",43.076014654537,-89.399642451567,25,"Npc",1,0,1,"0","0"],[3,"Dow Recruiter","",43.07550842555,-89.399381822662,25,"Npc",2,0,1,"0","0"] [4,"Protestor","",43.074933,-89.400438,25,"Npc",3,0,1,"0","0"],[5,"State Legislator","",43.074868061524,-89.402136196317,25,"Npc",4,0,1,"0","0"],[6,"Marchers Bascom","",43.075296413877,-89.403374183615,25,"Node",22,0,1,"0","0"] [7,"Mary","",43.074997865584,-89.404967573966,25,"Npc",7,0,1,"0","0"]]},"returnCode":0,"returnCodeDescription":null}

如何获取值:location_id,名称,纬度,经度。谢谢,米哈尔。


阅读 260

收藏
2020-07-27

共1个答案

小编典典

使用手动解析,您可以这样实现:

            JSONArray  pages     =  new JSONArray(jsonString);
            for (int i = 0; i < pages.length(); ++i) {
                JSONObject rec = pages.getJSONObject(i);
                JSONObject jsonPage =rec.getJSONObject("page");
                String address = jsonPage.getString("url");
                String name = jsonPage.getString("name");
                String status =  jsonPage.getString("status");
}

在您的案例中,请注意您的外部元素数据是JSONObject类型,然后您有了一个JSONArray

我的json文件:

[{"page":{"created_at":"2011-07-04T12:01:00Z","id":1,"name":"Unknown Page","ping_at":"2011-07-04T12:06:00Z","status":"up","updated_at":"2011-07-04T12:01:00Z","url":"http://www.iana.org/domains/example/","user_id":2}},{"page":{"created_at":"2011-07-04T12:01:03Z","id":3,"name":"Down Page","ping_at":"2011-07-04T12:06:03Z","status":"up","updated_at":"2011-07-04T12:01:03Z","url":"http://www.iana.org/domains/example/","user_id":2}}]

请注意,我的从[开始,这意味着一个数组,但您的是从{开始,然后您在内部有[数组。如果使用调试器运行它,则可以准确看到json对象中的内容。

还有更好的方法,例如:

  1. Jackson
  2. Jackson-JR(轻量级Jackson)
  3. GSON

所有这些都可以用于将Java对象转换为JSON表示形式。它还可以用于将JSON字符串转换为等效的Java对象。

2020-07-27