java - 编辑从解析的 JSON 字符串中检索到的字符串

标签 java android json

到目前为止,我的图书列表代码运行良好。稍后我将发出 URL 请求,目前我正在研究该功能。然而,这里是Screenshot我的输出。它的作用是,对于我的作者部分,作者姓名以方括号打印,成熟度评级以带下划线的大写字母打印。我无法弄清楚如何以更用户友好的方式编辑我的输出。

这是我的 Java 类。

MainActivity.java

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<Books> books = BookUtils.extractBooks();

        // Find a reference to the {@link ListView} in the layout
        ListView bookListView = (ListView) findViewById(R.id.list);

        // Create a new {@link ArrayAdapter} of earthquakes
        BookAdapter adapter = new BookAdapter(this, books);

        // Set the adapter on the {@link ListView}
        // so the list can be populated in the user interface
        bookListView.setAdapter(adapter);
    }
}

BookAdapter.java

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;


public class BookAdapter extends ArrayAdapter<Books> {

    public BookAdapter(Context context, List<Books> books){
        super(context, 0, books);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View listItemView = convertView;
        if (listItemView == null){
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.book_list_item, parent, false);
        }

        Books currentBook = getItem(position);

        TextView title = (TextView)listItemView.findViewById(R.id.book_title);
        title.setText(currentBook.getTitle());

        TextView authors = (TextView)listItemView.findViewById(R.id.book_author);
        authors.setText(currentBook.getAuthors());

        TextView publisher = (TextView)listItemView.findViewById(R.id.book_publisher);
        publisher.setText(currentBook.getPublisher());

        TextView publishingDate = (TextView)listItemView.findViewById(R.id.book_publishing_date);
        publishingDate.setText(currentBook.getPublishedDate());

        TextView language = (TextView)listItemView.findViewById(R.id.book_language);
        language.setText(currentBook.getLanguage());

        TextView pageCount = (TextView)listItemView.findViewById(R.id.book_page_count);
        pageCount.setText(currentBook.getCount());

        TextView printType = (TextView)listItemView.findViewById(R.id.book_print_type);
        printType.setText(currentBook.getPrintType());

        TextView maturityRating = (TextView)listItemView.findViewById(R.id.book_maturity_rating);
        maturityRating.setText(currentBook.getMaturityRating());

        return listItemView;
    }
}

书籍.java

public class Books {
    private String mTitle;
    private String mAuthors;

    private String mPublisher;
    private String mPublishingDate;
    private String mLanguage;

    private String mCount;
    private String mPrintType;
    private String mMaturityRating;

    public Books(String title, String authors, String publisher, String publishingDate, String language, String count, String printType, String maturityRating) {
        mTitle = title;
        mAuthors = authors;

        mPublisher = publisher;
        mPublishingDate = publishingDate;
        mLanguage = language;

        mCount = count;
        mPrintType = printType;
        mMaturityRating = maturityRating;
    }

    public String getTitle() {return mTitle;}
    public String getAuthors(){return mAuthors;}

    public String getPublisher(){return mPublisher;}
    public String getPublishedDate(){return mPublishingDate;}
    public String getLanguage(){return mLanguage;}

    public String getCount(){return mCount;}
    public String getPrintType(){return mPrintType;}
    public String getMaturityRating(){return mMaturityRating;}
}

BookUtils.java

import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public final class BookUtils {

    private static final String SAMPLE_JSON_RESPONSE = "{\n" +
            " \"kind\": \"books#volumes\",\n" +
            " \"totalItems\": 1117,\n" +
            " \"items\": [\n" +
            "  {\n" +
            "   \"kind\": \"books#volume\",\n" +
            "   \"id\": \"IEk2m00o9_IC\",\n" +
            "   \"etag\": \"+odAmEu8Vk0\",\n" +
            "   \"selfLink\": \"https://www.googleapis.com/books/v1/volumes/IEk2m00o9_IC\",\n" +
            "   \"volumeInfo\": {\n" +
            "    \"title\": \"Android Apps Security\",\n" +
            "    \"authors\": [\n" +
            "     \"Sheran Gunasekera\"\n" +
            "    ],\n" +
            "    \"publisher\": \"Apress\",\n" +
            "    \"publishedDate\": \"2012-09-12\",\n" +
            "    \"description\": \"Android Apps Security provides guiding principles for how to best design and " +
            "develop Android apps with security in mind. It explores concepts that can be used to secure apps and how " +
            "developers can use and incorporate these security features into their apps. This book will provide developers with " +
            "the information they need to design useful, high-performing, and secure apps that expose end-users to as little risk " +
            "as possible. Overview of Android OS versions, features, architecture and security. Detailed examination of areas where " +
            "attacks on applications can take place and what controls should be implemented to protect private user data In-depth guide " +
            "to data encryption, authentication techniques, enterprise security and applied real-world examples of these concepts What you’ll " +
            "learn How to identify data that should be secured How to use the Android APIs to ensure confidentiality and integrity of data " +
            "How to build secure apps for the enterprise About Public Key Infrastructure, encryption APIs and how to implement them in apps " +
            "About owners, access control lists and permissions to allow user control over App properties About client-server apps and how to manage " +
            "authentication, transport layer encryption and server-side security Who this book is for This book is for intermediate and experienced Android " +
            "app developers that are already familiar with writing apps from scratch. It discusses mechanisms on how apps can be secured so that private, end-user " +
            "data is kept secure on the device and while in transit. If you’re just embarking on the path to Android development, then this book " +
            "may prove to be a useful companion to other developer guides. Table of Contents Android Architecture & Security Controls " +
            "The Foundation of an App Who Has Access? Designing and Developing 3 Sample Apps Using PKI & Encryption Interfacing with Web " +
            "Services Writing for the Enterprise Designing and Developing 3 More Sample Apps Publishing and Selling Your Apps Malware, Spyware " +
            "and Your End-User API Reference\",\n" +
            "    \"industryIdentifiers\": [\n" +
            "     {\n" +
            "      \"type\": \"ISBN_13\",\n" +
            "      \"identifier\": \"9781430240624\"\n" +
            "     },\n" +
            "     {\n" +
            "      \"type\": \"ISBN_10\",\n" +
            "      \"identifier\": \"1430240628\"\n" +
            "     }\n" +
            "    ],\n" +
            "    \"readingModes\": {\n" +
            "     \"text\": true,\n" +
            "     \"image\": true\n" +
            "    },\n" +
            "    \"pageCount\": 248,\n" +
            "    \"printType\": \"BOOK\",\n" +
            "    \"categories\": [\n" +
            "     \"Computers\"\n" +
            "    ],\n" +
            "    \"maturityRating\": \"NOT_MATURE\",\n" +
            "    \"allowAnonLogging\": true,\n" +
            "    \"contentVersion\": \"1.1.1.0.preview.3\",\n" +
            "    \"imageLinks\": {\n" +
            "     \"smallThumbnail\": \"http://books.google.com/books/content?id=IEk2m00o9_IC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api\",\n" +
            "     \"thumbnail\": \"http://books.google.com/books/content?id=IEk2m00o9_IC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api\"\n" +
            "    },\n" +
            "    \"language\": \"en\",\n" +
            "    \"previewLink\": \"http://books.google.ca/books?id=IEk2m00o9_IC&printsec=frontcover&dq=android&hl=&cd=1&source=gbs_api\",\n" +
            "    \"infoLink\": \"http://books.google.ca/books?id=IEk2m00o9_IC&dq=android&hl=&source=gbs_api\",\n" +
            "    \"canonicalVolumeLink\": \"http://books.google.ca/books/about/Android_Apps_Security.html?hl=&id=IEk2m00o9_IC\"\n" +
            "   },\n" +
            "   \"saleInfo\": {\n" +
            "    \"country\": \"CA\",\n" +
            "    \"saleability\": \"NOT_FOR_SALE\",\n" +
            "    \"isEbook\": false\n" +
            "   },\n" +
            "   \"accessInfo\": {\n" +
            "    \"country\": \"CA\",\n" +
            "    \"viewability\": \"PARTIAL\",\n" +
            "    \"embeddable\": true,\n" +
            "    \"publicDomain\": false,\n" +
            "    \"textToSpeechPermission\": \"ALLOWED\",\n" +
            "    \"epub\": {\n" +
            "     \"isAvailable\": true,\n" +
            "     \"acsTokenLink\": \"http://books.google.ca/books/download/Android_Apps_Security-sample-epub.acsm?id=IEk2m00o9_IC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api\"\n" +
            "    },\n" +
            "    \"pdf\": {\n" +
            "     \"isAvailable\": true,\n" +
            "     \"acsTokenLink\": \"http://books.google.ca/books/download/Android_Apps_Security-sample-pdf.acsm?id=IEk2m00o9_IC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api\"\n" +
            "    },\n" +
            "    \"webReaderLink\": \"http://books.google.ca/books/reader?id=IEk2m00o9_IC&hl=&printsec=frontcover&output=reader&source=gbs_api\",\n" +
            "    \"accessViewStatus\": \"SAMPLE\",\n" +
            "    \"quoteSharingAllowed\": false\n" +
            "   },\n" +
            "   \"searchInfo\": {\n" +
            "    \"textSnippet\": \"This book will provide developers with the information they need to design useful, high-performing, and secure apps that expose end-users to as little risk as possible. Overview of Android OS versions, features, architecture and security.\"\n" +
            "   }\n" +
            "  }\n" +
            " ]\n" +
            "}";
    private BookUtils() {
    }

    public static ArrayList<Books>extractBooks(){
        ArrayList<Books> books = new ArrayList<>();

        // Try to parse the SAMPLE_JSON_RESPONSE. If there's a problem with the way the JSON
        // is formatted, a JSONException exception object will be thrown.
        // Catch the exception so the app doesn't crash, and print the error message to the logs.
        try {

            JSONObject jsonResponse = new JSONObject(SAMPLE_JSON_RESPONSE);
            JSONArray booksArray = jsonResponse.getJSONArray("items");

            for(int i = 0; i < booksArray.length(); i++){
                JSONObject currentBook = booksArray.getJSONObject(i);
                JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
                String title = volumeInfo.getString("title");
                String authors = volumeInfo.getString("authors");
                String publisher = volumeInfo.getString("publisher");
                String publishdDate = volumeInfo.getString("publishedDate");
                String language = volumeInfo.getString("language");
                String pageCount = volumeInfo.getString("pageCount");
                String printType = volumeInfo.getString("printType");
                String maturityRating = volumeInfo.getString("maturityRating");

                Books book = new Books(title, authors, publisher, publishdDate, language, pageCount, printType, maturityRating);
                books.add(book);
            }


        } catch (JSONException e) {

            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }

        // Return the list of earthquakes
        return books;
    }
}

最佳答案

问题出在Stringauthors = volumeInfo.getString("authors");

因为authors是一个数组,所以你需要使用getJSONArray而不是getString,如下所示:

JSONArray authorsArray = volumeInfo.getJSONArray("authors");

这将为您提供作者数组,但由于 Book bean 中有简单的 String 类型,因此您需要准备一个字符串并附加所有作者,如下所示。

处理作者数组的 BookUtils 代码 fragment :

for(int i = 0; i < booksArray.length(); i++){

        JSONObject currentBook = booksArray.getJSONObject(i);
        JSONObject volumeInfo = currentBook.getJSONObject("volumeInfo");
        JSONArray authorsArray = volumeInfo.getJSONArray("authors");
        String authors = "";
        for(int i=0; i<authorsArray.length();i++) {
            authors = authors +","+authorsArray.getString(i);
        }

        //set the other strings as is

        Books book = new Books(title, authors, publisher, publishdDate, language, pageCount, printType, maturityRating);
        books.add(book);
    }

关于java - 编辑从解析的 JSON 字符串中检索到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40326632/

相关文章:

php - json_encode 的斜线问题。为什么以及如何解决?

java - Eclipse "autosave before build"不工作?

Android Studio - 保存用户数据

java - 无法解析 Android Studio 上的 R.layout.splash

Android TextToSpeech setLanguage 适用于模拟器,但不适用于手机

Android:水平对齐 ProgressBar 并在 ConstraintLayout 中启用比例

java - 映射 JoinColum 值而不是 JSON 中的关联

json - Node JS : Validating request type (checking for JSON or HTML)

java - 使用 Bloch 的 Builder 模式是否会影响内存和性能?

java - 使用 Date 获取昨天的日期