【问题标题】:Java class from json with same name来自 json 的同名 Java 类
【发布时间】:2017-04-07 09:17:32
【问题描述】:

我有一个 JSON 对象,如下所示:

...
    {
       "url": "checkout.bodenusa.com/en-US"
    },
    {
       "url": [
            ".bonton.com/checkout/",
            ".bonton.com/CheckoutView"
        ]
    }
...

对于响应服务器,我的 Java 类应该是什么样子的。

我试试这个sn-p,但是不正确:

@SerializedName("url")
@Expose
private List<String> urlList = null;
@SerializedName("url")
@Expose
private String url;

【问题讨论】:

  • 这是无效的 json:{"1"}, {"2"}
  • 您的数据是无效的 JSON 变量
  • 使 URL 对象如下:"url": ["1", "2"]
  • @n00dl3 我不只是样本,我以为你自己想好了。我更正了我的样本。
  • 这是一个糟糕的设计,我的意思是在 json 中从 String 切换到 String[] 听起来是个糟糕的主意。我猜你需要实现某种Deserializer。但如果你有选择的话,我建议你只使用 string[]。

标签: java json gson


【解决方案1】:

创建一个类似的模型

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

public class Model {

    @SerializedName("url")
    @Expose
    private List<String> url = null;
    @SerializedName("apply")
    @Expose
    private Apply apply;
    @SerializedName("controls")
    @Expose
    private Controls controls;
    @SerializedName("remove")
    @Expose
    private Remove remove;

    public List<String> getUrl() {
        return url;
    }

    public void setUrl(List<String> url) {
        this.url = url;
    }

    public Apply getApply() {
        return apply;
    }

    public void setApply(Apply apply) {
        this.apply = apply;
    }

    public Controls getControls() {
        return controls;
    }

    public void setControls(Controls controls) {
        this.controls = controls;
    }

    public Remove getRemove() {
        return remove;
    }

    public void setRemove(Remove remove) {
        this.remove = remove;
    }


    public class Controls {

        @SerializedName("promo")
        @Expose
        private String promo;
        @SerializedName("total")
        @Expose
        private String total;
        @SerializedName("orderTotal")
        @Expose
        private String orderTotal;
        @SerializedName("coupon")
        @Expose
        private String coupon;

        public String getPromo() {
            return promo;
        }

        public void setPromo(String promo) {
            this.promo = promo;
        }

        public String getTotal() {
            return total;
        }

        public void setTotal(String total) {
            this.total = total;
        }

        public String getOrderTotal() {
            return orderTotal;
        }

        public void setOrderTotal(String orderTotal) {
            this.orderTotal = orderTotal;
        }

        public String getCoupon() {
            return coupon;
        }

        public void setCoupon(String coupon) {
            this.coupon = coupon;
        }

    }

    public class Remove {

        @SerializedName("type")
        @Expose
        private String type;
        @SerializedName("submit")
        @Expose
        private String submit;
        @SerializedName("timeout")
        @Expose
        private Integer timeout;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getSubmit() {
            return submit;
        }

        public void setSubmit(String submit) {
            this.submit = submit;
        }

        public Integer getTimeout() {
            return timeout;
        }

        public void setTimeout(Integer timeout) {
            this.timeout = timeout;
        }

    }

    public class Apply {

        @SerializedName("type")
        @Expose
        private String type;
        @SerializedName("submit")
        @Expose
        private String submit;
        @SerializedName("timeout")
        @Expose
        private Integer timeout;

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        public String getSubmit() {
            return submit;
        }

        public void setSubmit(String submit) {
            this.submit = submit;
        }

        public Integer getTimeout() {
            return timeout;
        }

        public void setTimeout(Integer timeout) {
            this.timeout = timeout;
        }

    }

}

将此类与 Gson 的自定义 TypeAdapter 一起使用。然后它将适用于 List 和 Object 响应。

ArrayAdapter 类

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public class ArrayAdapterFactory implements TypeAdapterFactory {

    @Override
    @SuppressWarnings({"unchecked", "rawtypes"})
    public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {

        TypeAdapter<T> typeAdapter = null;
        try {
            if (type.getRawType() == List.class || type.getRawType() == ArrayList.class) {

                typeAdapter = new ArrayAdapter(gson,
                        (Class) ((ParameterizedType) type.getType())
                                .getActualTypeArguments()[0]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return typeAdapter;

    }

}

ArrayAdapterFactory 类

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


class ArrayAdapter<T> extends TypeAdapter<List<T>> {

    private Class<T> adapterclass;
    private Gson gson;

    public ArrayAdapter(Gson gson, Class<T> adapterclass) {
        this.adapterclass = adapterclass;
        this.gson = gson;
    }

    @Override
    public List<T> read(JsonReader reader) throws IOException {

        List<T> list = new ArrayList<T>();

        final JsonToken token = reader.peek();
        System.out.println(token);
        // Handling of Scenario 2( Check JavaDoc for the class) :
        if (token == JsonToken.STRING || token == JsonToken.NUMBER ||
                token == JsonToken.BOOLEAN) {
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_OBJECT) {
            // Handling of Scenario 1(Check JavaDoc for the class) :
            T inning = (T) gson.fromJson(reader, adapterclass);
            list.add(inning);
        } else if (token == JsonToken.BEGIN_ARRAY) {
            reader.beginArray();
            while (reader.hasNext()) {
                @SuppressWarnings("unchecked")
                T inning = (T) gson.fromJson(reader, adapterclass);
                list.add(inning);
            }
            reader.endArray();
        }

        return list;
    }

    @Override
    public void write(JsonWriter writer, List<T> value) throws IOException {

    }


}

并像这样注册适配器工厂,

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

【讨论】:

  • 一个问题。我有日期反序列化 .setDateFormat("MM/dd/yyyy")。现在我有错误 com.google.gson.JsonSyntaxException: 4/10/2017,我如何在 ArrayAdapter 或 ArrayAdapterFactory 中传输反序列化到日期?
【解决方案2】:
public class Example {

private String url;

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

}

使用这个link 来生成 POJO 的

【讨论】:

  • 再想一想。我得到了数组。
  • 用我提供的链接试试你的 json。
猜你喜欢
  • 2014-04-13
  • 1970-01-01
  • 2018-04-29
  • 2016-05-14
  • 2015-11-09
  • 1970-01-01
  • 2023-03-05
  • 2013-01-13
  • 1970-01-01
相关资源
最近更新 更多