简体   繁体   English

从服务器解析嵌套的 JSON

[英]Parsing nested JSON from a server

I am working on an android project that parses JSON from a file on a server and converting the data into java objects to display the data using text views.我正在开发一个 android 项目,该项目从服务器上的文件解析 JSON,并将数据转换为 java 对象以使用文本视图显示数据。

The JSON file that I am parsing is based on a collection of books.我正在解析的 JSON 文件基于一系列书籍。 Within each book entry is an author which has nested child elements for the last and first name of that author.在每个图书条目中都有一个作者,该作者具有该作者姓氏和名字的嵌套子元素。 Some entries can have multiple authors.有些条目可以有多个作者。

JSON file: 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 Parser: 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);
        }
    }

What is the best way I can accomplish this?我能做到这一点的最佳方法是什么?

Use Gson by google, in your gradle add:使用谷歌的 Gson,在你的 gradle 中添加:

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

and you get it like:你会得到它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM