Java 将 JSONArray 转换为 List<Object>?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32133655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:04:24  来源:igfitidea点击:

Converting JSONArray to List<Object>?

javajsongson

提问by FernandoPaiva

I'm trying deserializes a JSONArray to List. To do it I'm trying use Gson but I can't understand why doesn't works and all values of JSON are null.

我正在尝试将 JSONArray 反序列化为 List。为此,我正在尝试使用 Gson,但我不明白为什么不起作用并且 JSON 的所有值都为空。

How could I do this ?

我怎么能这样做?

JSON

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"
          } }
    ] }

Deserializes

反序列化

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());
                            }

Class Noticia

班级通知

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;

回答by ziviland

You parse json, that looks like

你解析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"
      }
] }

You need to make another object Item and parse a list of them.

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

public class Item{
    Noticia noticia; 
}

Or you can interate through JSONArray, get field "noticia" from each then parse Noticia object from given JSONObject.

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

回答by Atul

I think the problem could be something to do with toString() on JSONArray. But are you using obj.getAsJsonArray method?

我认为问题可能与 JSONArray 上的 toString() 有关。但是你使用 obj.get作为JsonArray 方法吗?

Try this:

尝试这个:

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

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

回答by cн?dk

There are two problems with your code :

您的代码有两个问题:

  1. First is that you are using a getJsonArray()to get the array, which isn't part of Gsonlibrary, you need to use getAsJsonArray()method instead.
  2. Second is that you are using array.toString()which isn't obvious because for the fromJsonmethod you need a jsonArrayas parameter and not Stringand that will cause you parse problems, just remove it.
  1. 首先是你使用 agetJsonArray()来获取数组,它不是Gson库的一部分,你需要使用 getAsJsonArray()方法来代替。
  2. 其次是您正在使用array.toString()哪个并不明显,因为对于该fromJson方法,您需要一个jsonArrayas 参数而不是String这会导致您解析问题,只需将其删除即可。

And use the following code to convert your jsonArrayto List<Noticia>:

并使用以下代码将您的转换jsonArrayList<Noticia>

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

And your whole code will be:

你的整个代码将是:

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());
}

回答by Saurabh

Noticia.java

通知.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 + "]";
    }
}

Result.java

结果.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 + "]";
    }

}

Item.java

项目.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 + "]";
    }
}

Main.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);
    }
}

Final result

最后结果

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]]]]