如何使用Google GSON库解析下面的json?

时间:2014-10-10 06:53:49

标签: java android gson

这是我从服务器获取的json响应,

{
 "awards": [
    "31",
    "33",
    "44",
    "45",
    "46",
    "48"
 ]
}

但是当我尝试使用下面的代码解析它时

@SerializedName("awards")
  private UserAwards[] awards;

  public class UserAwards {

  }

它给了我以下例外:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 247.

请帮我找到解决方法。

3 个答案:

答案 0 :(得分:0)

检查link,如果你不能自己做json反对。

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Generated;
import javax.validation.Valid;
import com.google.gson.annotations.Expose;

@Generated("org.jsonschema2pojo")
public class UserAwards {

    @Expose
    @Valid
    private List<String> awards = new ArrayList<String>();

    public List<String> getAwards() {
        return awards;
    }

    public void setAwards(List<String> awards) {
        this.awards = awards;
    }

}

答案 1 :(得分:0)

这是用于解析:

Gson gson = new GsonBuilder().setFieldNamingPolicy(
                        FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
userAwards= gson.fromJson(jsonResponse.toString(), UserAwards.class);

你的班级应该像

public class UserAwards{

    @Expose
    private ArrayList<String> awards;
}

加上set和get方法:)

答案 2 :(得分:0)

解析如下:

private void parseResponse(final Reader p_response) {
    m_handler.post(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (p_response != null) {
                Gson m_gson = new GsonBuilder().setFieldNamingStrategy(
                        FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
                UserAwards m_details = m_gson.fromJson(p_response,
                        UserAwards.class);
                if (m_details != null) {

                      for (int i = 0; i < m_details.awards.length; i++) {
                        System.err.println("IDs======"
                                + m_details.awards[i].toString());
                        }
                    }

还可以按照以下方式制作POJO课程:

public class UserAwards {

     public List<String> awards = new ArrayList<String>();
 }