将JSON数据解析为字符串

huangapple go评论73阅读模式
英文:

paring JSON data as string

问题

public class QueryUtils {

    private QueryUtils() {
    }

    private final static String QUERY_UTILS_URL = "{  \"kind\": \"books#volumes\",  \"totalItems\": 392,  \"items\": [    {      \"kind\": \"books#volume\",      \"id\": \"qKFDDAAAQBAJ\",      \"etag\": \"REv5wZ4Dkek\",      \"selfLink\": \"https://www.googleapis.com/books/v1/volumes/qKFDDAAAQBAJ\",      \"volumeInfo\": {        \"title\": \"Android\",        \"authors\": [          \"P.K. Dixit\"        ],        \"publisher\": \"Vikas Publishing House\",        \"publishedDate\": \"2014\",        \"description\": \"Android is a movement that has transferred data from laptop to hand-held devices like mobiles. Though there are alternate technologies that compete with Android, but it is the front runner in mobile technology by a long distance. Good knowledge in basic Java will help you to understand and develop Android technology and apps. Many universities in India and across the world are now teaching Android in their syllabus, which shows the importance of this subject. This book can be read by anyone who knows Java and XML concepts. It includes a lot of diagrams along with explanations to facilitate better understanding by students. This book aptly concludes with a project that uses Android, which will greatly benefit students in learning the practical aspects of Android. Key Features • Instructions in designing different Android user interfaces • Thorough explanations of all activities • JSON • Android-based project to aid practical understanding\",        \"industryIdentifiers\": [          {            \"type\": \"ISBN_13\",            \"identifier\": \"9789325977884\"          },          {            \"type\": \"ISBN_10\",            \"identifier\": \"9325977885\"          }        ],        \"readingModes\": {          \"text\": false,          \"image\": true        },        \"pageCount\": 372,        \"printType\": \"BOOK\",        \"categories\": [          \"Computers\"        ],        \"averageRating\": 3,        \"ratingsCount\": 1,        \"maturityRating\": \"NOT_MATURE\",        \"allowAnonLogging\": true,        \"contentVersion\": \"preview-1.0.0\",        \"panelizationSummary\": {          \"containsEpubBubbles\": false,          \"containsImageBubbles\": false        },        \"imageLinks\": {          \"smallThumbnail\": \"http://books.google.com/books/content?id=qKFDDAAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api\",          \"thumbnail\": \"http://books.google.com/books/content?id=qKFDDAAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api\"        },        \"language\": \"en\",        \"previewLink\": \"http://books.google.com.eg/books?id=qKFDDAAAQBAJ&printsec=frontcover&dq=android&hl=&cd=1&source=gbs_api\",        \"infoLink\": \"https://play.google.com/store/books/details?id=qKFDDAAAQBAJ&source=gbs_api\",        \"canonicalVolumeLink\": \"https://play.google.com/store/books/details?id=qKFDDAAAQBAJ\"      },      \"saleInfo\": {        \"country\": \"EG\",        \"saleability\": \"FOR_SALE\",        \"isEbook\": true,        \"listPrice\": {          \"amount\": 236.25,          \"currencyCode\": \"EGP\"        },        \"retailPrice\": {          \"amount\": 236.25,          \"currencyCode\": \"EGP\"        },        \"buyLink\": \"https://play.google.com/store/books/details?id=qKFDDAAAQBAJ&rdid=book-qKFDDAAAQBAJ&rdot=1&source=gbs_api\",        \"offers\": [          {            \"finskyOfferType\": 1,            \"listPrice\": {              \"amountInMicros\": 236250000,              \"currencyCode\": \"EGP\"            },            \"retailPrice\": {              \"amountInMicros\": 236250000,              \"currencyCode\": \"EGP\"            }          }        ]      },      \"accessInfo\": {        \"country\": \"EG\",        \"viewability\": \"PARTIAL\",        \"embeddable\": true,        \"publicDomain\": false,        \"textToSpeechPermission\": \"ALLOWED\",        \"epub\": {          \"isAvailable\": false        },        \"pdf\": {          \"isAvailable\": true,          \"acsTokenLink\": \"http://books.google.com.eg/books/download/Android-sample-pdf.acsm?id=qKFDDAAAQBAJ&format=pdf&output=acs4_fulfillment_token&dl_type=sample&source=gbs_api\"        },        \"webReaderLink\": \"http://play.google.com/books/reader?id=qKFDDAAAQBAJ&hl=&printsec=frontcover&source=gbs_api\",        \"accessViewStatus\": \"SAMPLE\",        \"quoteSharingAllowed\": false      },      \"searchInfo\": {        \"textSnippet\": \"Many universities in India and across the world are now teaching Android in their syllabus, which shows the importance of this subject. This book can be read by anyone who knows Java and XML concepts.\"}}]}";

    public static ArrayList<CustomBookModel> bookModels() {
        ArrayList<CustomBookModel> bookModelArrayList = new ArrayList<>();

        try {
            JSONObject books = new JSONObject(QUERY_UTILS_URL);
            JSONArray booksArray = books.getJSONArray("items");
            for (int i = 0; i < booksArray.length(); i++) {
                JSONObject currentBook = booksArray.getJSONObject(i);
                JSONObject infoVolumes = currentBook.getJSONObject("volumeInfo");
                String title = infoVolumes.getString("title");
                String author = infoVolumes.getJSONArray("authors").getString(0);

                CustomBookModel book = new CustomBookModel(title, author);
                bookModelArrayList.add(book);
            }
        } catch (Exception e) {
            Log.e("QueryUtils", "problem parsing ....", e);
        }
        return bookModelArrayList;
    }
}
public class MainActivity extends AppCompatActivity {

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

        ArrayList<CustomBookModel> bookModels = QueryUtils.bookModels();

        // Use the bookModels data as needed
    }
}

(Note: I've fixed the JSON parsing error and made necessary corrections in the code to properly parse the JSON response and create CustomBookModel objects.)

英文:

i try to parse the json file as a string to use it to display this date in listview i tried like the course's video but i have this error but in video it works

 public class QueryUtils {
private QueryUtils(){
}
private final static String QUERY_UTILS_URL = &quot;{  \&quot;kind\&quot;: \&quot;books#volumes\&quot;,  \&quot;totalItems\&quot;: 392,  \&quot;items\&quot;: [    {      \&quot;kind\&quot;: \&quot;books#volume\&quot;,      \&quot;id\&quot;: \&quot;qKFDDAAAQBAJ\&quot;,      \&quot;etag\&quot;: \&quot;REv5wZ4Dkek\&quot;,      \&quot;selfLink\&quot;: \&quot;https://www.googleapis.com/books/v1/volumes/qKFDDAAAQBAJ\&quot;,      \&quot;volumeInfo\&quot;: {        \&quot;title\&quot;: \&quot;Android\&quot;,        \&quot;authors\&quot;: [          \&quot;P.K. Dixit\&quot;        ],        \&quot;publisher\&quot;: \&quot;Vikas Publishing House\&quot;,        \&quot;publishedDate\&quot;: \&quot;2014\&quot;,        \&quot;description\&quot;: \&quot;Android is a movement that has transferred data from laptop to hand-held devices like mobiles. Though there are alternate technologies that compete with Android, but it is the front runner in mobile technology by a long distance. Good knowledge in basic Java will help you to understand and develop Android technology and apps. Many universities in India and across the world are now teaching Android in their syllabus, which shows the importance of this subject. This book can be read by anyone who knows Java and XML concepts. It includes a lot of diagrams along with explanations to facilitate better understanding by students. This book aptly concludes with a project that uses Android, which will greatly benefit students in learning the practical aspects of Android. Key Features • Instructions in designing different Android user interfaces • Thorough explanations of all activities • JSON • Android-based project to aid practical understanding\&quot;,        \&quot;industryIdentifiers\&quot;: [          {            \&quot;type\&quot;: \&quot;ISBN_13\&quot;,            \&quot;identifier\&quot;: \&quot;9789325977884\&quot;          },          {            \&quot;type\&quot;: \&quot;ISBN_10\&quot;,            \&quot;identifier\&quot;: \&quot;9325977885\&quot;          }        ],        \&quot;readingModes\&quot;: {          \&quot;text\&quot;: false,          \&quot;image\&quot;: true        },        \&quot;pageCount\&quot;: 372,        \&quot;printType\&quot;: \&quot;BOOK\&quot;,        \&quot;categories\&quot;: [          \&quot;Computers\&quot;        ],        \&quot;averageRating\&quot;: 3,        \&quot;ratingsCount\&quot;: 1,        \&quot;maturityRating\&quot;: \&quot;NOT_MATURE\&quot;,        \&quot;allowAnonLogging\&quot;: true,        \&quot;contentVersion\&quot;: \&quot;preview-1.0.0\&quot;,        \&quot;panelizationSummary\&quot;: {          \&quot;containsEpubBubbles\&quot;: false,          \&quot;containsImageBubbles\&quot;: false        },        \&quot;imageLinks\&quot;: {          \&quot;smallThumbnail\&quot;: \&quot;http://books.google.com/books/content?id=qKFDDAAAQBAJ&amp;printsec=frontcover&amp;img=1&amp;zoom=5&amp;edge=curl&amp;source=gbs_api\&quot;,          \&quot;thumbnail\&quot;: \&quot;http://books.google.com/books/content?id=qKFDDAAAQBAJ&amp;printsec=frontcover&amp;img=1&amp;zoom=1&amp;edge=curl&amp;source=gbs_api\&quot;        },        \&quot;language\&quot;: \&quot;en\&quot;,        \&quot;previewLink\&quot;: \&quot;http://books.google.com.eg/books?id=qKFDDAAAQBAJ&amp;printsec=frontcover&amp;dq=android&amp;hl=&amp;cd=1&amp;source=gbs_api\&quot;,        \&quot;infoLink\&quot;: \&quot;https://play.google.com/store/books/details?id=qKFDDAAAQBAJ&amp;source=gbs_api\&quot;,        \&quot;canonicalVolumeLink\&quot;: \&quot;https://play.google.com/store/books/details?id=qKFDDAAAQBAJ\&quot;      },      \&quot;saleInfo\&quot;: {        \&quot;country\&quot;: \&quot;EG\&quot;,        \&quot;saleability\&quot;: \&quot;FOR_SALE\&quot;,        \&quot;isEbook\&quot;: true,        \&quot;listPrice\&quot;: {          \&quot;amount\&quot;: 236.25,          \&quot;currencyCode\&quot;: \&quot;EGP\&quot;        },        \&quot;retailPrice\&quot;: {          \&quot;amount\&quot;: 236.25,          \&quot;currencyCode\&quot;: \&quot;EGP\&quot;        },        \&quot;buyLink\&quot;: \&quot;https://play.google.com/store/books/details?id=qKFDDAAAQBAJ&amp;rdid=book-qKFDDAAAQBAJ&amp;rdot=1&amp;source=gbs_api\&quot;,        \&quot;offers\&quot;: [          {            \&quot;finskyOfferType\&quot;: 1,            \&quot;listPrice\&quot;: {              \&quot;amountInMicros\&quot;: 236250000,              \&quot;currencyCode\&quot;: \&quot;EGP\&quot;            },            \&quot;retailPrice\&quot;: {              \&quot;amountInMicros\&quot;: 236250000,              \&quot;currencyCode\&quot;: \&quot;EGP\&quot;            }          }        ]      },      \&quot;accessInfo\&quot;: {        \&quot;country\&quot;: \&quot;EG\&quot;,        \&quot;viewability\&quot;: \&quot;PARTIAL\&quot;,        \&quot;embeddable\&quot;: true,        \&quot;publicDomain\&quot;: false,        \&quot;textToSpeechPermission\&quot;: \&quot;ALLOWED\&quot;,        \&quot;epub\&quot;: {          \&quot;isAvailable\&quot;: false        },        \&quot;pdf\&quot;: {          \&quot;isAvailable\&quot;: true,          \&quot;acsTokenLink\&quot;: \&quot;http://books.google.com.eg/books/download/Android-sample-pdf.acsm?id=qKFDDAAAQBAJ&amp;format=pdf&amp;output=acs4_fulfillment_token&amp;dl_type=sample&amp;source=gbs_api\&quot;        },        \&quot;webReaderLink\&quot;: \&quot;http://play.google.com/books/reader?id=qKFDDAAAQBAJ&amp;hl=&amp;printsec=frontcover&amp;source=gbs_api\&quot;,        \&quot;accessViewStatus\&quot;: \&quot;SAMPLE\&quot;,        \&quot;quoteSharingAllowed\&quot;: false      },      \&quot;searchInfo\&quot;: {        \&quot;textSnippet\&quot;: \&quot;Many universities in India and across the world are now teaching Android in their syllabus, which shows the importance of this subject. This book can be read by anyone who knows Java and XML concepts.\&quot;}}]}&quot;;
public static ArrayList&lt;CustomBookModel&gt; bookModels (){
ArrayList&lt;CustomBookModel&gt; bookModelArrayList = new ArrayList&lt;&gt;();
try{
JSONObject books = new JSONObject(QUERY_UTILS_URL);
JSONArray booksArray = new JSONArray(&quot;items&quot;);
for (int i = 0 ;i &lt; booksArray.length() ;i++ ){
JSONObject currentBook =booksArray.getJSONObject(i);
JSONObject infoVolumes = currentBook.getJSONObject(&quot;volumeInfo&quot;);
String title = infoVolumes.getString(&quot;title&quot;);
String author = infoVolumes.getString(&quot;authors&quot;);
CustomBookModel book = new CustomBookModel(title ,author);
bookModelArrayList.add(book);
}
} catch (Exception e) {
Log.e(&quot;QueryUtils&quot; , &quot;problem parsing ....&quot; , e);
}
return bookModelArrayList;
}}

but i have this error in logcat

 10-26 11:47:34.575 10591-10591/? I/art: Late-enabling -Xcheck:jni
10-26 11:47:34.575 10591-10591/? I/art: VMHOOK: rlim_cur : 0 pid:10591
10-26 11:47:34.653 10591-10591/com.example.bookslist W/System: ClassLoader referenced unknown path: /data/app/com.example.bookslist-1/lib/arm
10-26 11:47:34.703 10591-10591/com.example.bookslist W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter androidx.vectordrawable.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
10-26 11:47:34.771 10591-10591/com.example.bookslist I/art: Rejecting re-init on previously-failed class java.lang.Class&lt;androidx.core.view.ViewCompat$2&gt;
10-26 11:47:34.772 10591-10591/com.example.bookslist I/art: Rejecting re-init on previously-failed class java.lang.Class&lt;androidx.core.view.ViewCompat$2&gt;
10-26 11:47:34.911 10591-10591/com.example.bookslist E/QueryUtils: problem parsing ....
org.json.JSONException: Value items of type java.lang.String cannot be converted to JSONArray
at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.&lt;init&gt;(JSONArray.java:96)
at org.json.JSONArray.&lt;init&gt;(JSONArray.java:108)
at com.example.bookslist.QueryUtils.bookModels(QueryUtils.java:21)
at com.example.bookslist.MainActivity.onCreate(MainActivity.java:17)
at android.app.Activity.performCreate(Activity.java:6248)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1125)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2544)
at android.app.ActivityThread.access$900(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1394)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5845)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
10-26 11:47:35.029 10591-10605/com.example.bookslist I/Adreno-EGL: &lt;qeglDrvAPI_eglInitialize:379&gt;: EGL 1.4 QUALCOMM build: Nondeterministic_AU_msm8974_LA.BF.1.1.3__release_AU (I3fa967cfef)
OpenGL ES Shader Compiler Version: E031.28.00.02
Build Date: 09/29/15 Tue
Local Branch: mybranch14683032
Remote Branch: quic/master
Local Patches: NONE
Reconstruct Branch: NOTHING

and i still learning it but the course's video was did it and it worked

答案1

得分: 0

JSONArray booksArray = new JSONArray("items");

这会创建一个新的空json数组对象,然后创建一个名为booksArray的新变量,并将该变量设置为引用这个新创建的空数组对象。

这不是您获取JSONObject中的items数组的方法。您应该寻找类似于books.get("items")的内容。

更一般地说,这个json库的质量令人遗憾地很差;建议使用类似GSON或Jackson的库代替。
英文:

> JSONArray booksArray = new JSONArray(&quot;items&quot;);

This makes a new, empty json array object, and then creates a new variable named booksArray, and then sets that variable to be a reference to this newly created object, which is an empty array.

This is not how you fetch that items array in the JSONObject you have. You're looking for something like books.get(&quot;items&quot;).

More generally, that json library is deplorably bad; use something like GSON or Jackson instead.

答案2

得分: 0

请尝试这样:

public static ArrayList<CustomBookModel> bookModels (){
    ArrayList<CustomBookModel> bookModelArrayList = new ArrayList<>();

    try{
        JSONObject books = new JSONObject(QUERY_UTILS_URL);
        JSONArray booksArray = books.getJSONArray("items");
        for (int i = 0 ;i < booksArray.length() ;i++ ){
            JSONObject currentBook = booksArray.getJSONObject(i);
            JSONObject infoVolumes = currentBook.getJSONObject("volumeInfo");
            String title = infoVolumes.getString("title");
            String author = infoVolumes.getString("authors");

            CustomBookModel book = new CustomBookModel(title ,author);
            bookModelArrayList.add(book);
        }
    } catch (Exception e) {
       Log.e("QueryUtils" , "problem parsing ...." , e);
    }
    return bookModelArrayList;
}}
英文:

Try this :

public static ArrayList&lt;CustomBookModel&gt; bookModels (){
ArrayList&lt;CustomBookModel&gt; bookModelArrayList = new ArrayList&lt;&gt;();
try{
JSONObject books = new JSONObject(QUERY_UTILS_URL);
JSONArray booksArray = books.getJSONArray(&quot;items&quot;);
for (int i = 0 ;i &lt; booksArray.length() ;i++ ){
JSONObject currentBook =booksArray.getJSONObject(i);
JSONObject infoVolumes = currentBook.getJSONObject(&quot;volumeInfo&quot;);
String title = infoVolumes.getString(&quot;title&quot;);
String author = infoVolumes.getString(&quot;authors&quot;);
CustomBookModel book = new CustomBookModel(title ,author);
bookModelArrayList.add(book);
}
} catch (Exception e) {
Log.e(&quot;QueryUtils&quot; , &quot;problem parsing ....&quot; , e);
}
return bookModelArrayList;
}}

huangapple
  • 本文由 发表于 2020年10月26日 17:57:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64534883.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定