在Android上使用GSON解析JSON文件的问题

时间:2013-12-26 14:27:30

标签: android gson

我正在尝试解析Android应用程序的JSON文件。我设法在LogCat上查看文件内容,但我总是收到错误。 LogCat告诉我它期望一个字符串但是BEGIN_ARRAY。

主要活动类:

.../** Called when the activity is first created. 
 * @return */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Portrait only
    this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    //Remove title bar
            this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    //Remove notification bar
            this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);


            // Reading text file from assets folder
            StringBuffer sb = new StringBuffer();
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(getAssets().open(
                        "test.json")));
                String temp;
                while ((temp = br.readLine()) != null)
                    sb.append(temp);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    br.close(); // stop reading
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            String myjsonstring = sb.toString();
            Log.d("string: " , myjsonstring);


             Gson gson = new Gson();
              ShopHeader orderHeader = gson.fromJson(myjsonstring, ShopHeader.class);

              System.out.println("Shop Information --->");
              System.out.println("Shop id: " + orderHeader.getId());
              System.out.println("Shop url: " + orderHeader.getUrl());
              System.out.println("Shop created_at: " + orderHeader.getCreated_at());
              System.out.println("Shop updated_at: " + orderHeader.getUpdated_at());
              System.out.println("Shop name: " + orderHeader.getName());
              System.out.println("Shop phone: " + orderHeader.getPhone());
              System.out.println("Shop fax: " + orderHeader.getFax());
              System.out.println("Shop email: " + orderHeader.getEmail());
              System.out.println("Shop website_url: " + orderHeader.getWebsite_url());
              System.out.println("Shop detail: " + orderHeader.getDetail());
              System.out.println("Shop logo_url: " + orderHeader.getLogo_url());
              System.out.println("Shop logo_thumbnail_url: " + orderHeader.getLogo_thumbnail_url());
              System.out.println("Shop photos_urls: " + orderHeader.getPhotos_urls());
              System.out.println("Shop opening_hours: " + orderHeader.getOpening_hours());

              ArrayList<ShopContact> contact = orderHeader.getContact();
              for (int i=0; i<contact.size(); i++){
               System.out.println("Contact Detail --->");
               ShopContact contactDetail = contact.get(i);

              System.out.println("Contact title : " + contactDetail.getTitle()); 
              System.out.println("Contact first name : " + contactDetail.getFirst_name());
              System.out.println("Contact last name: " + contactDetail.getLast_name());

              System.out.println("Shop address_string: " + orderHeader.getAddress_string());

              ArrayList<ShopAddress> address = orderHeader.getAddress();
              for (int j=0; j<address.size(); j++){
               System.out.println("Address Detail --->");
               ShopAddress addressDetail = address.get(j);
               System.out.println("Address id: " + addressDetail.getId());
               System.out.println("Address url: " + addressDetail.getUrl());
               System.out.println("Address created_at: " + addressDetail.getCreated_at());
               System.out.println("Address updated_at: " + addressDetail.getUpdated_at());
               System.out.println("Address street_address: " + addressDetail.getStreet_address());
               System.out.println("Address extended_address: " + addressDetail.getExtended_address());
               System.out.println("Address postal_code: " + addressDetail.getPostal_code());
               System.out.println("Address locality: " + addressDetail.getLocality());
               System.out.println("Address country_code_alpha2: " + addressDetail.getCountry_code_alpha2());
               System.out.println("Address coordinates: " + addressDetail.getCoordinates());



               ArrayList<ShopBooklet> booklet = orderHeader.getBooklet();
                  for (int k=0; k<booklet.size(); k++){
                   System.out.println("Booklet Detail --->");
                   ShopBooklet bookletDetail = booklet.get(k);
                   System.out.println("Booklet id: " + bookletDetail.getId());
                   System.out.println("Booklet url: " + bookletDetail.getUrl());
                   System.out.println("Booklet created_at: " + bookletDetail.getCreated_at());
                   System.out.println("Booklet updated_at: " + bookletDetail.getUpdated_at());
                   System.out.println("Booklet title: " + bookletDetail.getTitle());
                   System.out.println("Booklet thumbnail_url: " + bookletDetail.getThumbnail_url());
                   System.out.println("Booklet document_url: " + bookletDetail.getDocument_url());
                   System.out.println("Booklet presented: " + bookletDetail.getPresented());

              }
              ...

修改:JSON的结构:

[
    {
        "id": "5295ca1e3131610014250000",
        "url": "http://api.site.com/v1/shops/5295ca1e3131610014250000.json",
        "created_at": "2013-11-27T11:31:58+01:00",
        "updated_at": "2013-12-12T17:27:04+01:00",
        "name": "NAME",
        "phone": "05 46 05 02 96",
        "fax": null,
        "email": "mail@orange.fr",
        "website_url": "http://api.site.com/",
        "detail": null,
        "logo_url": "http://s3.amazonaws.com/api.site.com/shops/logos/5295/ca1e/3131/6100/1425/0000/normal?1386586749",
        "logo_thumbnail_url": "http://s3.amazonaws.com/api.site.com/shops/logos/5295/ca1e/3131/6100/1425/0000/thumb/test.jpg?1386586749",
        "photos_urls": [
            "http://s3.amazonaws.com/api.site.com/shops/image1s/5295/ca1e/3131/6100/1425/0000/normal/test.jpg?1386604322"
        ],
        "opening_hours": [
            null,
            null,
            null,
            null,
            null,
            null,
            null
        ],
        "contact": {
            "title": "M.",
            "first_name": "First",
            "last_name": "Name"
        },
        "address_string": "Address",
        "address": {
            "id": "defe",
            "url": "http://api.site.com/v1/addresses/5295ca1e3131610014270000.json",
            "created_at": "2013-11-27T11:31:58+01:00",
            "updated_at": "2013-12-11T20:46:54+01:00",
            "street_address": "address",
            "extended_address": null,
            "postal_code": "40303",
            "locality": "City",
            "country_code_alpha2": "uk",
            "coordinates": [
                27.6232869,
                -8.0304642
            ]
        },
        "booklet": {
            "id": "dldl",
            "url": "http://api.site.com/v1/booklets/5295ca1e3131610014280000.json",
            "created_at": "2013-11-27T11:31:58+01:00",
            "updated_at": "2013-12-13T18:32:33+01:00",
            "title": "Name",
            "thumbnail_url": "http://s3.amazonaws.com/api.site.com/booklets/documents/5295/ca1e/3131/6100/1428/0000/thumb/name.png?1386955949",
            "document_url": "http://s3.amazonaws.com/api.site.com/booklets/documents/5295/ca1e/3131/6100/1428/0000/original/name.pdf?1386955949",
            "presented": false
        }
    }
]

编辑:这是标题类

import java.util.ArrayList;

public class ShopHeader {

    String id = null;
    String url = null;
    String created_at = null;
    String  updated_at = null;
    String name = null;
    String phone = null;
    String fax = null;
    String email = null;
    String website_url = null;
    String detail = null;
    String logo_url = null;
    String logo_thumbnail_url = null;
    String photos_urls = null;
    String opening_hours = null;
    ArrayList<ShopContact>contact;
    String address_string = null;
    ArrayList<ShopAddress>address;
    ArrayList<ShopBooklet>booklet;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getCreated_at() {
        return created_at;
    }
    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }
    public String getUpdated_at() {
        return updated_at;
    }
    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public String getFax() {
        return fax;
    }
    public void setFax(String fax) {
        this.fax = fax;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getWebsite_url() {
        return website_url;
    }
    public void setWebsite_url(String website_url) {
        this.website_url = website_url;
    }
    public String getDetail() {
        return detail;
    }
    public void setDetail(String detail) {
        this.detail = detail;
    }
    public String getLogo_url() {
        return logo_url;
    }
    public void setLogo_url(String logo_url) {
        this.logo_url = logo_url;
    }
    public String getLogo_thumbnail_url() {
        return logo_thumbnail_url;
    }
    public void setLogo_thumbnail_url(String logo_thumbnail_url) {
        this.logo_thumbnail_url = logo_thumbnail_url;
    }
    public String getPhotos_urls() {
        return photos_urls;
    }
    public void setPhotos_urls(String photos_urls) {
        this.photos_urls = photos_urls;
    }
    public String getOpening_hours() {
        return opening_hours;
    }
    public void setOpening_hours(String opening_hours) {
        this.opening_hours = opening_hours;
    }
    public ArrayList<ShopContact> getContact() {
        return contact;
    }
    public void setContact(ArrayList<ShopContact> contact) {
        this.contact = contact;
    }
    public String getAddress_string() {
        return address_string;
    }
    public void setAddress_string(String address_string) {
        this.address_string = address_string;
    }
    public ArrayList<ShopAddress> getAddress() {
        return address;
    }
    public void setAddress(ArrayList<ShopAddress> address) {
        this.address = address;
    }
    public ArrayList<ShopBooklet> getBooklet() {
        return booklet;
    }
    public void setBooklet(ArrayList<ShopBooklet> booklet) {
        this.booklet = booklet;
    }

}

Elevine请求的LogCat:

12-26 14:46:42.226: E/AndroidRuntime(1931): FATAL EXCEPTION: main
12-26 14:46:42.226: E/AndroidRuntime(1931): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.begital.votrebijoutier/com.begital.votrebijoutier.ShopActivity}: java.lang.IllegalStateException: This is not a JSON Array.
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.os.Looper.loop(Looper.java:137)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.ActivityThread.main(ActivityThread.java:4745)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at java.lang.reflect.Method.invokeNative(Native Method)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at java.lang.reflect.Method.invoke(Method.java:511)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at dalvik.system.NativeStart.main(Native Method)
12-26 14:46:42.226: E/AndroidRuntime(1931): Caused by: java.lang.IllegalStateException: This is not a JSON Array.
12-26 14:46:42.226: E/AndroidRuntime(1931):     at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at com.begital.votrebijoutier.ShopActivity.onCreate(ShopActivity.java:87)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.Activity.performCreate(Activity.java:5008)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-26 14:46:42.226: E/AndroidRuntime(1931):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-26 14:46:42.226: E/AndroidRuntime(1931):     ... 11 more
12-26 14:48:16.306: E/AndroidRuntime(2087): FATAL EXCEPTION: main
12-26 14:48:16.306: E/AndroidRuntime(2087): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.begital.votrebijoutier/com.begital.votrebijoutier.ShopActivity}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 659
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.os.Looper.loop(Looper.java:137)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.ActivityThread.main(ActivityThread.java:4745)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at java.lang.reflect.Method.invokeNative(Native Method)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at java.lang.reflect.Method.invoke(Method.java:511)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at dalvik.system.NativeStart.main(Native Method)
12-26 14:48:16.306: E/AndroidRuntime(2087): Caused by: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 659
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.Gson.fromJson(Gson.java:803)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.Gson.fromJson(Gson.java:768)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.Gson.fromJson(Gson.java:717)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.Gson.fromJson(Gson.java:689)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.begital.votrebijoutier.ShopActivity.onCreate(ShopActivity.java:89)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.Activity.performCreate(Activity.java:5008)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-26 14:48:16.306: E/AndroidRuntime(2087):     ... 11 more
12-26 14:48:16.306: E/AndroidRuntime(2087): Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 1 column 659
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.stream.JsonReader.nextString(JsonReader.java:821)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:358)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.internal.bind.TypeAdapters$13.read(TypeAdapters.java:346)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
12-26 14:48:16.306: E/AndroidRuntime(2087):     at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
12-26 14:48:16.306: E/AndroidRuntime(2087):     ... 19 more
12-26 15:00:37.516: E/AndroidRuntime(2355): FATAL EXCEPTION: main
12-26 15:00:37.516: E/AndroidRuntime(2355): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.begital.votrebijoutier/com.begital.votrebijoutier.ShopActivity}: com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_ARRAY

1 个答案:

答案 0 :(得分:0)

您的JSON是一个包含一个对象的数组。该对象映射到您的ShopHeader类。但是,在您的代码中,您尝试将该JSON作为单个ShopHeader对象读取:

ShopHeader orderHeader = gson.fromJson(myjsonstring, ShopHeader.class);

您需要告诉GSON将其作为数组或ShopHeader列表读取。以下可能有效:

List<ShopHeader> orderHeaders = gson.fromJson(myjsonstring, ShopHeader.class);
ShopHeader orderHeader = orderHeaders.get(0);