解析错误字段作为对象或数组 [英] Error parsing field as object or array

查看:174
本文介绍了解析错误字段作为对象或数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的JSON字符串,这我假设反序列化。现在的问题是:由于这串来自于一台服务器,我不能改变它,我需要反序列化的POJO。你可以看到 Grafs 键为每个分区不同的值。之一是一个对象的其他阵列。我该如何处理呢?

i have the following Json string, which I'm suppose to deserialize. The problem is: since this string comes from a server I can't change it and I need to deserialize as POJO. You can see that the Grafs keys have different values for each subarea. One is an object an the other an array. How can I handle this?

{
"Status": "true",
"Result: {
    "rows": {
        "row": {
            "status": true,
            "subareas": [
                {
                    "nome": "Associacao Utente",
                    "id": 9,
                    "grafs": {
                        "rows": {
                            "id": 6,
                            "nome": "Associacao Utente",
                            "tipo": "PIE",
                            "serv": "MV_AS_UTENTE_POR_NEGOCIO",
                            "periodo": "ANO"
                        }
                    }
                }, {
                    "nome": "Chaves",
                    "id": 60,
                    "grafs": {
                        "rows": [
                            {
                                "id": 35,
                                "nome": "Chaves Criados por ano",
                                "tipo": "LINHA",
                                "serv": "MV_ASSOC_TOTAL_CHAVES",
                                "periodo": "ANO"
                            }, {
                                "id": 592,
                                "nome": "Chaves Associado Ao User Portal",
                                "tipo": "BAR",
                                "serv": "MV_ASSOC_USER_CHAVES",
                                "periodo": "TODOS"
                            }, {
                                "id": 593,
                                "nome": "Chaves Associado Ao Negocios",
                                "tipo": "BAR",
                                "serv": "MV_ASSOC_CHAVES",
                                "periodo": "TODOS"
                            }
                        ]
                    }
                }
            ]
        }
    }
}

}

下面我如下班。

public class Example {
    private String Status;
    private Result Result;

    public String getStatus() {
        return Status;
    }

    public void setStatus(String status) {
        Status = status;
    }

    public Result getResult() {
        return Result;
    }

    public void setResult(Result result) {
        Result = result;
    }

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

}

public class Result {
    private Rows rows;

    public Rows getRows() {
        return rows;
    }

    public void setRows(Rows rows) {
        this.rows = rows;
    }

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

public class Grafs {
    private List<Rows_> rows = new ArrayList<>();

    public List<Rows_> getRows() {

        return rows;
    }

    public void setRows(List<Rows_> Rows) {
        this.rows = Rows;
    }


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

public class Row {
    private Boolean status;
    private List<Subarea> subareas = new ArrayList<>();

    public Boolean getStatus() {
        return status;
    }

    public void setStatus(Boolean status) {
        this.status = status;
    }

    public List<Subarea> getSubareas() {
        return subareas;
    }

    public void setSubareas(List<Subarea> subareas) {
        this.subareas = subareas;
    }

    @Override
    public String toString() {
        return "Row [status=" + status + ", subareas=" + subareas + "]";
    }
}

public class Row_ {
    private Integer id;
    private String nome;
    private String serv;
    private String periodo;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getServ() {
        return serv;
    }

    public void setServ(String serv) {
        this.serv = serv;
    }

    public String getPeriodo() {
        return periodo;
    }

    public void setPeriodo(String periodo) {
        this.periodo = periodo;
    }

    @Override
    public String toString() {
        return "Row_ [id=" + id + ", nome=" + nome + ", serv=" + serv
               + ", periodo=" + periodo + "]";
    }
}

public class Rows {
    private Row row;

    public Row getRow() {
        return row;
    }

    public void setRow(Row row) {
        this.row = row;
    }

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

public class Rows_ {
    private Row_ row;

    public Row_ getRow() {
        return row;
    }

    public void setRow(Row_ row) {
        this.row = row;
    }
}

public class Subarea {
    private String nome;
    private Integer id;

    private Grafs grafs;

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Grafs getGrafs() {
        return grafs;
    }

    public void setGrafs(Grafs grafs) {
        this.grafs = grafs;
    }

    @Override
    public String toString() {
        return "Subarea [nome=" + nome + ", id=" + id + ", grafs=" + grafs
               + "]";
    }
}

使用这些类,我发现了以下错误:

Using these classes I'm getting the following error:

Expected BEGIN_ARRAY  but was BEGIN_OBJECT at line 13 column 18.

我宣布Rows_作为一个ArrayList和它遇到的物体来代替。但第二Rows_确实是一个数组。我怎样才能解决这个问题?

I declared Rows_ as an arraylist and it encounters an object instead. But the second Rows_ is an array indeed. How can i address this?

一个数组元素应该仍然呈现为数组。这就是为什么我使用的阵列。但它给我描述的错误。

Arrays with one element should still be rendered as arrays. That's why I used arrays. But it's giving the error I described.

感谢您的帮助。我真的AP preciate它。

Thanks for your help. I really appreciate it.

推荐答案

您可以使用<一个href=\"https://google-gson.google$c$c.com/svn/trunk/gson/docs/javadocs/com/google/gson/TypeAdapterFactory.html\"相对=nofollow> TypeAdapterFactory 做转换。这里是一个工厂,这将是功能添加到您所有的列表成员类型 -

You can use TypeAdapterFactory to do the conversion. Here is a factory that will add that functionality to all of your List member types --

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

public class SingletonListTypeAdapterFactory implements TypeAdapterFactory {
     public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> typeToken) {

       Type type = typeToken.getType();
       if (typeToken.getRawType() != List.class
           || !(type instanceof ParameterizedType)) {
         return null;
       }
       Type elementType = ((ParameterizedType) type).getActualTypeArguments()[0];
       TypeAdapter<?> elementAdapter = gson.getAdapter(TypeToken.get(elementType));
       TypeAdapter<T> arrayAdapter = gson.getDelegateAdapter(this, typeToken);
       return (TypeAdapter<T>) newSingtonListAdapter((TypeAdapter<Object>) elementAdapter, (TypeAdapter<List<Object>>) arrayAdapter);
     }

     private <E> TypeAdapter<List<E>> newSingtonListAdapter(
         final TypeAdapter<E> elementAdapter,
         final TypeAdapter<List<E>> arrayAdapter) {
       return new TypeAdapter<List<E>>() {

         public void write(JsonWriter out, List<E> value) throws IOException {
           if(value == null || value.isEmpty()) {
             out.nullValue();
           } else if(value.size() == 1) {
            elementAdapter.write(out, value.get(0));
           } else {
             arrayAdapter.write(out, value);
           }
         }

         public List<E> read(JsonReader in) throws IOException {
           if (in.peek() != JsonToken.BEGIN_ARRAY) {
             E obj = elementAdapter.read(in);
             return Collections.singletonList(obj);
           }
           return arrayAdapter.read(in);
         }
       };
     }
   }

作为奖励,它也序列化以同样的方式,如果需要的话。如果你也想为序列化数组,替换方法通过调用 arrayAdapter.write

要你,当构建添加到您的GSON -

To you, add to your gson when building --

Gson gson = new GsonBuilder().registerTypeAdapterFactory(new SingletonListTypeAdapterFactory())
        .create();

这篇关于解析错误字段作为对象或数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆