首页 > 解决方案 > 将 POJO 转换为数组列表

问题描述

我已经在 Android 改造中为 Jackson 制作了 POJO 类,并且我得到了我的 json,我可以使用 FOR Loop 获取所有元素,但是有没有一种快速的方法可以将它们放入 array 或 arraylist ,或者有什么快速的方法来获取它们?

这是故事:我从我的 php 服务器获取这个 json :

-----------------------------------------------------------------
{
    "TableUsers": [
        {
            "id": "1",
            "name": "James",
            "score": "2450"
        },
        {
            "id": "2",
            "name": "Sam",
            "score": "1780"
        }
    ],
    "TableGames": [
        {
            "id": "1",
            "game": "PES",
            "gener": "football"
        },
        {
            "id": "2",
            "game": "DeltaForce",
            "gener": "action"
        }
    ]
}
-----------------------------------------------------------------

然后使用这个 json 的在线网站,我为 Jackson 2.x 制作了 POJO:

这是 POJO:

-----------------------------------com.gn.gamenet2021.GetAllJsonData.java-----------------------------------

package com.gn.gamenet2021;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"TableUsers",
"TableGames"
})
public class GetAllJsonData {

@JsonProperty("TableUsers")
private List<TableUser> tableUsers = null;
@JsonProperty("TableGames")
private List<TableGame> tableGames = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("TableUsers")
public List<TableUser> getTableUsers() {
return tableUsers;
}

@JsonProperty("TableUsers")
public void setTableUsers(List<TableUser> tableUsers) {
this.tableUsers = tableUsers;
}

@JsonProperty("TableGames")
public List<TableGame> getTableGames() {
return tableGames;
}

@JsonProperty("TableGames")
public void setTableGames(List<TableGame> tableGames) {
this.tableGames = tableGames;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.gn.gamenet2021.TableGame.java-----------------------------------

package com.gn.gamenet2021;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"game",
"gener"
})
public class TableGame {

@JsonProperty("id")
private String id;
@JsonProperty("game")
private String game;
@JsonProperty("gener")
private String gener;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("id")
public String getId() {
return id;
}

@JsonProperty("id")
public void setId(String id) {
this.id = id;
}

@JsonProperty("game")
public String getGame() {
return game;
}

@JsonProperty("game")
public void setGame(String game) {
this.game = game;
}

@JsonProperty("gener")
public String getGener() {
return gener;
}

@JsonProperty("gener")
public void setGener(String gener) {
this.gener = gener;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
-----------------------------------com.gn.gamenet2021.TableUser.java-----------------------------------

package com.gn.gamenet2021;

import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"id",
"name",
"score"
})
public class TableUser {

@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
@JsonProperty("score")
private String score;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("id")
public String getId() {
return id;
}

@JsonProperty("id")
public void setId(String id) {
this.id = id;
}

@JsonProperty("name")
public String getName() {
return name;
}

@JsonProperty("name")
public void setName(String name) {
this.name = name;
}

@JsonProperty("score")
public String getScore() {
return score;
}

@JsonProperty("score")
public void setScore(String score) {
this.score = score;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}

//------------------------------------------------ ------------------------------------------

使用这些库:

implementation 'com.fasterxml.jackson.core:jackson-databind:2.10.1'
    implementation 'com.fasterxml.jackson.core:jackson-core:2.10.1'
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.10.1'
    implementation 'com.squareup.retrofit2:retrofit:2.6.1'
    implementation 'com.squareup.retrofit2:converter-jackson:2.6.1'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'

//------------------------------------------------ ------------------------------------------

api接口:

public interface GetJsonApiClient {

    @GET("downloadAllData.php")
    Call<GetAllJsonData> getJsonData();
}

//------------------------------------------------ ------------------------------------------

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

public class RestUtil {
    private static RestUtil self;
    private String API_BASE_URL = "http://192.168.0.45/";
    private Retrofit retrofit;

    private RestUtil(){
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient httpClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        OkHttpClient client = new OkHttpClient().newBuilder()
                .readTimeout(50, TimeUnit.SECONDS)
                .connectTimeout(25, TimeUnit.SECONDS).build();

        Retrofit.Builder builder =
                new Retrofit.Builder()
                .baseUrl(API_BASE_URL)
                .client(client)
                .addConverterFactory(JacksonConverterFactory.create());
        retrofit = builder.client(httpClient).build();
    }

    public static RestUtil getInstance(){
        if (self == null){
            synchronized (RestUtil.class){
                if (self == null){
                    self = new RestUtil();
                }
            }
        }
        return self;
    }

    public Retrofit getRetrofit(){
        return retrofit;
    }
}

//------------------------------------------------ -------------------------------------------------------- 在 MainActivity :

GetJsonApiClient client = RestUtil.getInstance().getRetrofit().create(GetJsonApiClient.class);
        Call<GetAllJsonData> call = client.getJsonData();
        call.enqueue(new Callback<GetAllJsonData>() {
            @Override
            public void onResponse(Call<GetAllJsonData> call, Response<GetAllJsonData> response) {
                
                // here easly I can access data using for loop :
                for(int i = 0; i< response.body().getTableUsers().size(); i++){
                    
                    String test = response.body().getTableUsers().get(i).getName();
                    // my question is : is there a faster way reading this data and inserting them into sqlite database ?!
                    // with this for loop I can get data into Array and send them to sqlite Database , but is there a better faster way ?
                    
                }

            }

            @Override
            public void onFailure(Call<GetAllJsonDatum> call, Throwable t) {

                Toast.makeText(MainActivity.this, "onFailure :\n" + t, Toast.LENGTH_SHORT).show();
            }
        });

标签: androidjsonclassobjectjackson

解决方案


推荐阅读