2

在我的应用程序中,我使用 facebook sdk for android 接收来自 Facebook 的通知。但是方法返回的数据response.toString()是json格式的。

我需要知道如何将其转换为简单的人类可读格式,以便可以使用它们在文本字段中查看?

这就是我从图形资源管理器中得到的。必需的字符串是“标题”

{
  "id": "10000115768434",
  "name": "Nauman Aslam",
  "notifications": {
    "data": [
      {
        "id": "notif_10000357346818423_6543370",
        "from": {
          "name": "Muhammad Asad Iqbal",
          "id": "56342467433"
        },
        "to": {
          "name": "Nauman Aslam",
          "id": "324545436818423"
        },
        "created_time": "2014-03-28T20:09:02+0000",
        "updated_time": "2014-03-28T20:16:05+0000",
        "title": "Muhammad Asad Iqbal and Smat Kazmi also commented on Muhammad Asad Iqbal's photo.",
        "link": "http://www.facebook.com/photo.php?fbid=4040070417111&se",
        "application": {
          "name": "Photos",
          "id": "54635732"
        },
        "unread": 1
      },
4

2 回答 2

2

您需要在线查找 JSONparser 库并使用它们,或者如果您愿意,您可以编写自己的 JSONparser 类并解析 java 对象中的数据(顺便说一下,JSON 响应通常是人类可读的,它只是作为一个对象出现或数组或对象)。如果您想编写自己的 JSONparser 类,那么在您发布 JSONresponse 并且我们看到响应的格式之前,我们无法建议您从哪里开始。

我要说的一件事是首先检查您的 JSON 响应的格式。了解格式非常重要,因为如果 JSONresponse 以“对象数组对象”的格式出现,则必须使用“JSONObject --> JSONArray ->> JSONObject”对其进行解码,否则程序将崩溃。单击此处并将您的 json 响应复制粘贴到文本框中,它将显示它的格式。

如果您想从 JSON 解码的基础知识开始单击此处并在 stackoverflow 上查看我的答案,它非常基础,但如果您只是开始处理 JSONresponses,它可能是一个好的开始。

编辑

根据您的 JSONresponse 它从大括号开始,这意味着响应是一个 JSONObject 但我没有看到整个 JSONresponse 并且缺少一些括号所以我的回答可能没有意义但如果您理解它可以按照步骤操作

您要做的第一件事是将响应保存在“字符串”对象中并创建一个 JSONObject 并通过传递响应来初始化它。然后你想要从中提取“通知”对象,所以你再次创建第二个 JSONObject 这个对象只会从字符串中提取“通知”对象

那么您希望提取 JSONArray“数据”,以便从 JSONObject 定义一个 JSONArray 和 getJSONArray(“data”)。他们再次需要 JSONObject 来仅提取“标题”对象。

总结

    Create JSONObject and pass the response String to it
    Create second JSONObject from it
    Create JSONArray and use getJSONArray("___") method on you JSONObject
    and finally create last JSONObject inside a for loop if you have more than one notification 
    and use getString("title") method on that object

您的 JSON 响应不完整,所以我可能错了,但您可以试一试。

于 2014-03-29T18:29:00.037 回答
1

When you get a response string in json format there are libraries that allows you to turn your string in a dictionary type.

If you want a web site that helps you view a json string in readable by hummans go here Online JSON Viewer. Paste your code in the first page then go to viewer tab, you'll see the name of the keys and the values.

于 2014-03-29T17:53:41.247 回答