gson 是否将JSONArray转换为列表< Object>?

sulc1iza  于 2022-11-23  发布在  其他
关注(0)|答案(5)|浏览(168)

我正在尝试将一个JSONArray反序列化为List。为此,我尝试使用Gson,但我不明白为什么不起作用,JSON的所有值都是null。
我怎么能这么做呢?

JSON格式

{ "result" : [ 
      { "Noticia" : { 
            "created" : "2015-08-20 19:58:49",
            "descricao" : "tttttt",
            "id" : "19",
            "image" : null,
            "titulo" : "ddddd",
            "usuario" : "FERNANDO PAIVA"
          } },
      { "Noticia" : { 
            "created" : "2015-08-20 19:59:57",
            "descricao" : "hhhhhhhh",
            "id" : "20",
            "image" : "logo.png",
            "titulo" : "TITULO DA NOTICIA",
            "usuario" : "FERNANDO PAIVA"
          } }
    ] }

反序列化

List<Noticia> lista = new ArrayList<Noticia>();
                            Gson gson = new Gson();
                            JSONArray array = obj.getJSONArray("result");

                            Type listType = new TypeToken<List<Noticia>>() {}.getType();
                            lista = gson.fromJson(array.toString(), listType);

                            //testing - size = 2 but value Titulo is null
                            Log.i("LISTSIZE->", lista.size() +"");
                            for(Noticia n:lista){
                                Log.i("TITULO", n.getTitulo());
                            }

船级社声明

public class Noticia implements Serializable {
    private static final long serialVersionUID = 1L;

    private Integer id;
    private String titulo;
    private String descricao;
    private String usuario;
    private Date created;
    private String image;
smdncfj3

smdncfj31#

您的程式码有两个问题:
1.首先,您使用getJsonArray()来获取数组,它不是Gson库的一部分,您需要使用**getAsJsonArray()**方法来代替。
1.第二,您使用的是array.toString(),这并不明显,因为对于fromJson方法,您需要jsonArray作为参数,而不是String,这将导致解析问题,只需删除它。
并使用以下代码将jsonArray转换为List<Noticia>

Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);

整个代码将是:

Gson gson = new Gson();
JSONArray array = obj.getAsJsonArray("result");

Type type = new TypeToken<List<Noticia>>() {}.getType();
List<Noticia> lista = gson.fromJson(array, type);

//testing - size = 2 but value Titulo is null
Log.i("LISTSIZE->", lista.size() +"");
for(Noticia n:lista){
   Log.i("TITULO", n.getTitulo());
}
s4n0splo

s4n0splo2#

通知.java

public class Noticia {
    private String created;
    private String descricao;
    private String id;
    private String image;
    private String titulo;
    private String usuario;
    public String getCreated() {
        return created;
    }
    public void setCreated(String created) {
        this.created = created;
    }
    public String getDescricao() {
        return descricao;
    }
    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getImage() {
        return image;
    }
    public void setImage(String image) {
        this.image = image;
    }
    public String getTitulo() {
        return titulo;
    }
    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }
    public String getUsuario() {
        return usuario;
    }
    public void setUsuario(String usuario) {
        this.usuario = usuario;
    }
    @Override
    public String toString() {
        return "Noticia [created=" + created + ", descricao=" + descricao
                + ", id=" + id + ", image=" + image + ", titulo=" + titulo
                + ", usuario=" + usuario + "]";
    }
}

结果.java

public class Result {
    private Noticia Noticia;

    public Noticia getNoticia() {
        return Noticia;
    }

    public void setNoticia(Noticia noticia) {
        Noticia = noticia;
    }

    @Override
    public String toString() {
        return "Result [Noticia=" + Noticia + "]";
    }

}

项目.java

import java.util.List;

public class Item {
    private List<Result> result;

    public List<Result> getResult() {
        return result;
    }

    public void setResult(List<Result> result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return "Item [result=" + result + "]";
    }
}

主要.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.testgson.beans.Item;

public class Main {
    private static Gson gson;

    static {
        gson = new GsonBuilder().create();
    }

    public static void main(String[] args) {
        String j = "{\"result\":[{\"Noticia\":{\"created\":\"2015-08-20 19:58:49\",\"descricao\":\"tttttt\",\"id\":\"19\",\"image\":null,\"titulo\":\"ddddd\",\"usuario\":\"FERNANDO PAIVA\"}},{\"Noticia\":{\"created\":\"2015-08-20 19:59:57\",\"descricao\":\"hhhhhhhh\",\"id\":\"20\",\"image\":\"logo.png\",\"titulo\":\"TITULO DA NOTICIA\",\"usuario\":\"FERNANDO PAIVA\"}}]}";
        Item r = gson.fromJson(j, Item.class);
        System.out.println(r);
    }
}

最终结果

Item [result=[Result [Noticia=Noticia [created=2015-08-20 19:58:49, descricao=tttttt, id=19, image=null, titulo=ddddd, usuario=FERNANDO PAIVA]], Result [Noticia=Noticia [created=2015-08-20 19:59:57, descricao=hhhhhhhh, id=20, image=logo.png, titulo=TITULO DA NOTICIA, usuario=FERNANDO PAIVA]]]]
sy5wg1nm

sy5wg1nm3#

解析json,看起来像

{ "result" : [ 
  { 
        "created" : "2015-08-20 19:58:49",
        "descricao" : "tttttt",
        "id" : "19",
        "image" : null,
        "titulo" : "ddddd",
        "usuario" : "FERNANDO PAIVA"
   },
  { 
        "created" : "2015-08-20 19:59:57",
        "descricao" : "hhhhhhhh",
        "id" : "20",
        "image" : "logo.png",
        "titulo" : "TITULO DA NOTICIA",
        "usuario" : "FERNANDO PAIVA"
      }
] }

您需要创建另一个对象Item并解析它们的列表。

public class Item{
    Noticia noticia; 
}

或者,您可以通过JSONArray进行交互,从每个JSONArray中获取字段“noticia”,然后从给定的JSONObject中解析Noticia对象。

a1o7rhls

a1o7rhls4#

我认为问题可能与JSONArray上的toString()有关。但是您使用的是obj.getAsJsonArray方法吗?
试试看:

JSONArray arr = obj.getAsJsonArray("result"); 

            Type listType = new TypeToken<List<Noticia>>() {
            }.getType();
            return new Gson().fromJson(arr , listType);
hlswsv35

hlswsv355#

Kotlin示例:

我们以JSONArry的形式获得响应

call.enqueue(object : Callback<JsonArray> {
        override fun onResponse(call: Call<JsonArray>, response: Response<JsonArray>) {

            val list = response.body().toString()
            val gson = Gson()
            val obj: CitiesList? = gson.fromJson(list, CitiesList::class.java)
            cityLiveData.value = obj!!
           

        }

        override fun onFailure(call: Call<JsonArray>, t: Throwable) {
          
        }

    })

此处CitiesList CitiesList::class.java是城市对象的数组列表

class CitiesList : ArrayList<CitiesListItem>()

使用GSON之前,在Gradle中添加依赖性

dependencies {

implementation 'com.google.code.gson:gson:2.8.8'

}

相关问题