【问题标题】:Read json array from a json object with gson使用 gson 从 json 对象中读取 json 数组
【发布时间】:2020-05-05 05:38:18
【问题描述】:

我想从 API 获取带有 JSON 的 JSON 对象列表。例如affiliate.itunes 但是对于 gson,我不能抛出 jsonObject,我必须为此母校使用 java JSONObject 和 JSONArray 类。 是否可以使用 gson lib 完全处理这个问题?

这是我复制到我的 android raw 文件夹中的 json 文件

这是我的代码

public class MainActivity extends AppCompatActivity {

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

        GsonBuilder builder = new GsonBuilder();
        Gson gson = builder.create();

        InputStream inputStream = getResources().openRawResource(R.raw.file);
        String jsonStr = streamToString(inputStream);

        try {
            JSONObject jsonObject = new JSONObject(jsonStr);
            JSONArray jsonArray = jsonObject.getJSONArray("results");
            Type type = new TypeToken<List<BandJsonResult>>(){}.getType();
            List<BandJsonResult> jsonResults = gson.fromJson(jsonArray.toString(),type);

            for(int i = 0 ; i < jsonResults.size() ; i++){
                Log.e("JSON " + i ,jsonResults.get(i).toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
    private String streamToString(InputStream stream) {

        InputStreamReader reader = new InputStreamReader(stream);
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuilder result = new StringBuilder();
        String line = "";
        try {
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
        }catch (IOException ex){
            ex.printStackTrace();
        }
        return result.toString();
    }
}

【问题讨论】:

    标签: android json gson


    【解决方案1】:

    Gson 默认使用反射来(反)序列化类(除非您提供自定义适配器),另请参阅 Gson 用户指南中的 this example。根据屏幕截图,您可以添加这两个类:

    // You can give these classes any name
    class ApiResponse {
        // Uses the field names for (de-)serialization by default, but you can also
        // specify custom names using @SerializedName
        private int resultCount;
        private List<BandResult> results;
    }
    
    class BandResult {
        // You can also use enums and then either name the enum constants the same
        // as the values, or annotate the enum constants with @SerializedName
        private String wrapperType;
        private String kind;
        private int artistId;
        ...
    }
    

    然后在调用Gson.fromJson时使用它们:

    ApiResponse apiResponse = gson.fromJson(jsonStr, ApiResponse.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多