从服务器解析嵌套的JSON

时间:2020-03-31 20:11:21

标签: java android json

我正在研究一个Android项目,该项目从服务器上的文件解析JSON,并将数据转换为Java对象,以使用文本视图显示数据。

我正在解析的JSON文件基于一本书集。每本书的条目中都有一个作者,该作者嵌套了该作者姓氏和名字的子元素。有些条目可以有多个作者。

JSON文件:

{
  "bib": {
    "book": [
      {
        "year": "1994",
        "title": "TCP/IP Illustrated",
        "author": {
          "last": "Stevens",
          "first": "W."
        },
        "publisher": "Addison-Wesley",
        "price": "65.95"
      },
      {
        "year": "1992",
        "title": "Advanced Programming in the Unix environment",
        "author": {
          "last": "Stevens",
          "first": "W."
        },
        "publisher": "Addison-Wesley",
        "price": "65.95"
      },
      {
        "year": "2000",
        "title": "Data on the Web",
        "author": [
          {
            "last": "Abiteboul",
            "first": "Serge"
          },
          {
            "last": "Buneman",
            "first": "Peter"
          },
          {
            "last": "Suciu",
            "first": "Dan"
          }
        ],
        "publisher": "Morgan Kaufmann Puslishers",
        "price": "39.95"
      },
      {
        "year": "2012",
        "title": "Professional Android 4 application development",
        "author": {
          "last": "Meier",
          "first": "Reto"
        },
        "publisher": "ndianapolis : John Wiley and Sons",
        "price": "33.47"
      },
      {
        "year": "2017",
        "title": "Java Programming for Beginners: Learn the fundamentals of programming with Java",
        "author": {
          "last": "Lassoff",
          "first": "Mark"
        },
        "publisher": "Packt Publishing",
        "price": "23.99"
      },
      {
        "year": "2005",
        "title": "Head First Java",
        "author": [
          {
            "last": "Sierra",
            "first": "Kathy"
          },
          {
            "last": "Bates",
            "first": "Bert"
          },
        ],
        "publisher": "MO'Reilly Media; 2 edition",
        "price": "21.25"
      },
      {
        "year": "2013",
        "title": "XML for Dummies",
        "author": {
            "last": "Tittel",
            "first": "Ed"
        },
        "publisher": "Wiley; 4th edition",
        "price": "14.99"
      },
      {
        "year": "2019",
        "title": "Java XML and JSON: Document Processing for Java SE",
        "author": {
          "last": "Friesen",
          "first": "Jeff"
        },
        "publisher": "Apress; 2nd ed. edition",
        "price": "65.95"
      },
      {
        "year": "2016",
        "title": "Java Programming for Android Developers For Dummies (For Dummies (Computers))",
        "author": {
          "last": "Burd",
          "first": "Barry A."
        },
        "publisher": "John Wiley and Sons; 2nd edition",
        "price": "16.99"
      }
    ]
  }
}

JSON解析器:

  private class parseJSON extends AsyncTask<Void, Void, List<Book>> {

        private final String TAG = parseJSON.class.getSimpleName();
        @Override
        protected List<Book> doInBackground(Void... voids) {
            Log.i(TAG, "Start Async to get books.");
            ArrayList<Book> bookArray = new ArrayList<>(0);

            String jsonUrl = getApplication().getString(R.string.json_feed);
            HttpHandler httpHandler = new HttpHandler();
            String jsonString = httpHandler.makeJsonServiceCall(jsonUrl);

            Log.i(TAG, "Response from url: " + jsonString);

            if( jsonString != null) {
                try {
                    JSONObject root = new JSONObject(jsonString);

                    // Get JSON array node.
                    JSONArray books = root.getJSONObject("bib").getJSONArray("book");
                    // Looping through all the books.
                    for (int i = 0; i < books.length(); i++) {
                        JSONObject jsonBook = books.getJSONObject(i);


                        String year = jsonBook.getString("year");
                        String title = jsonBook.getString("title");


                        String author = jsonBook.getString("author");

                        String publisher = jsonBook.getString("publisher");
                        String price = "£" + jsonBook.getString("price");

                        final Book bookObject = new Book(year, title, author, publisher, price);

                        //Add the new books to our result array.
                        bookArray.add(bookObject);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return bookArray;
        }

        @Override
        protected void onPostExecute( List<Book> books) {
            super.onPostExecute(books);
            Log.e(TAG, "Populate UI recycler view with json converted data.");
            bookList.setValue(books);
        }
    }

实现此目标的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

使用Google的Gson,在您的gradle中添加:

实现'com.google.code.gson:gson:2.8.6'

您将得到:

Book bookObject = new Gson().fromJson("json", Book.class);