私はアンドロイドが初めてで、JSON解析を学ぶためのアプリを作成しています。 GoogleブックスAPIのJSONデータをアプリケーション用に解析したいのですが、APIのModelクラスを作成できません。 (私はフィット見たように)私は4つのモデルクラスを作成し与えられたGoogleBooks APIのモデルクラス
{
"kind": "books#volumes",
"totalItems": 1591,
"items": [
{
"kind": "books#volume",
"id": "An4_e3Cr3zAC",
"etag": "DWmqBRkB8dw",
"selfLink": "https://www.googleapis.com/books/v1/volumes/An4_e3Cr3zAC",
"volumeInfo": {
"title": "The Rules of the Game",
"authors": [
"Neil Strauss"
],
"publisher": "Canongate Books",
"publishedDate": "2011-09-29",
"description": "If you want to play The Game you need to know The Rules This book is not a story. It is a how-to book. This Stylelife Challenge is not meant to be read. It is meant to be performed. Whatever experience level you have, whatever strengths and weaknesses you may have, whether you're a virgin or a Don Juan, the stage has been set for you to perform at your highest capacity. The Stylelife Challenge is a simple, easy-to-follow guide to the basics of approaching and attracting women. The Challenge is simply what works best and fastest. Neil Strauss spent four years gathering this knowledge, living it and sharing it. He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques. The result: A month-long workout program for your social, attraction, dating and seduction skills.",
"industryIdentifiers": [
{
"type": "ISBN_13",
"identifier": "9781847673558"
},
{
"type": "ISBN_10",
"identifier": "1847673554"
}
],
"readingModes": {
"text": true,
"image": true
},
"pageCount": 352,
"printType": "BOOK",
"categories": [
"Biography & Autobiography"
],
"averageRating": 3.5,
"ratingsCount": 82,
"maturityRating": "NOT_MATURE",
"allowAnonLogging": true,
"contentVersion": "1.7.6.0.preview.3",
"imageLinks": {
"smallThumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://books.google.co.in/books/content?id=An4_e3Cr3zAC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "en",
"previewLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&printsec=frontcover&dq=game&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.co.in/books/about/The_Rules_of_the_Game.html?hl=&id=An4_e3Cr3zAC"
},
"saleInfo": {
"country": "IN",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 399.0,
"currencyCode": "INR"
},
"retailPrice": {
"amount": 279.3,
"currencyCode": "INR"
},
"buyLink": "http://books.google.co.in/books?id=An4_e3Cr3zAC&dq=game&hl=&buy=&source=gbs_api",
"offers": [
{
"finskyOfferType": 1,
"listPrice": {
"amountInMicros": 3.99E8,
"currencyCode": "INR"
},
"retailPrice": {
"amountInMicros": 2.793E8,
"currencyCode": "INR"
}
}
]
},
"accessInfo": {
"country": "IN",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-epub.acsm?id=An4_e3Cr3zAC&format=epub&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"pdf": {
"isAvailable": true,
"acsTokenLink": "http://books.google.co.in/books/download/The_Rules_of_the_Game-sample-pdf.acsm?id=An4_e3Cr3zAC&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api"
},
"webReaderLink": "http://books.google.co.in/books/reader?id=An4_e3Cr3zAC&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "He's tested the specific material in this book on over 13,000 men of varying ages, nationalities and backgrounds. Part practical application and part sequel, this is the further adventures of Style and his game techniques."
}
}
]
}
:ここではデータ内に表示のための最初の結果のためのJSONデータがあります。ここに4つのクラスすべてのコードがあります。すべてのクラスには、それぞれのセッターとゲッターが含まれています。
public class BookItems {
String kind;
String id;
String etag;
String selfLink;
}
public class BookVolumeInfo {
String title;
String publisher;
String publishedDate;
String description;
long pageCount;
float averageRating;
long ratingsCount;
String maturityRating;
}
public class BookAuthors {
String authors;
}
public class BookCategories {
String categories;
}
可能であれば、これをすべて1つのクラスで実行したいと思います。私がコードを実行したとき、私はその本のタイトルを取得していません。ここに私のプロジェクトのメインコードです。
public class MainActivity extends AppCompatActivity {
public static final String Logcat = "vmech";
Button searchButton;
EditText editTextSearch;
TextView textViewDisplayResult;
String newText;
String urlstring;
public static final String MyAPIKey = "Your_Api_Key";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchButton = (Button) findViewById(R.id.buttonSerch);
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
textViewDisplayResult = (TextView) findViewById(R.id.textViewDisplayResult);
searchButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
newText = editTextSearch.getText().toString();
if(newText.length()>0){
newText = newText.replace(" ", "+");
urlstring = "https://www.googleapis.com/books/v1/volumes?q=";
urlstring = urlstring + newText + "&maxResults=5" + "&key=" + MyAPIKey;
// Log.e(Logcat,"URL created successfully");
// Log.i(Logcat,"URL created successfully");
}
else {
Toast.makeText(MainActivity.this, "Please enter a book name to search.", Toast.LENGTH_LONG).show();
// Log.e(Logcat,"Search field empty");
// Log.i(Logcat,"Search field empty");
}
new JSONTask().execute(urlstring);
//Toast.makeText(MainActivity.this, "Search Button Clicked.", Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
//super.onCreateOptionsMenu(menu);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
Toast.makeText(this, "This is the Settings item", Toast.LENGTH_LONG).show();
return true;
}
public class JSONTask extends AsyncTask<String, String, List<BookVolumeInfo>>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected List<BookVolumeInfo> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader bufferedReader = null;
// URL url = null;
try {
URL url = new URL(urlstring);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream inputstream = connection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputstream));
StringBuffer stringbuffer = new StringBuffer();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringbuffer.append(line);
}
String finalJson = stringbuffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("items");
List<BookVolumeInfo> bookVolumeInfoList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++){
JSONObject finalObject = parentArray.getJSONObject(i);
BookVolumeInfo bookVolumeInfo = new BookVolumeInfo();
BookAuthors bookAuthors = new BookAuthors();
BookCategories bookCategories = new BookCategories();
bookVolumeInfo.setTitle(finalObject.getString("title"));
bookVolumeInfo.setDescription(finalObject.getString("description"));
bookVolumeInfo.setAverageRating((float) finalObject.getDouble("averageRating"));
bookAuthors.setAuthors(finalObject.getString("authors"));
bookCategories.setCategories(finalObject.getString("categories"));
bookVolumeInfoList.add(bookVolumeInfo);
}
return bookVolumeInfoList;
} catch (IOException e){
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
{
connection.disconnect();
}
try {
if (bufferedReader != null){
bufferedReader.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(List<BookVolumeInfo> result) {
super.onPostExecute(result);
textViewDisplayResult.setText((CharSequence) result);
}
}
}
私はそれがすべてのエラーを与えていませんが、私はそれがAndroidのモニタウィンドウで述べている本を探していたときに、「タイトルが見つからない」のコードを実行しています。
助けてください。
使用http://www.jsonschema2pojo.org/あなたの 'JSON'をあなたの生成した' POJO'オブジェクトに追加します - 詳細はanswerを見てください:http://stackoverflow.com/questions/37642963/difference-between-string-scanning-and-json-parsing-for-a-json -string –