java - Android JSON 无法从 START_OBJECT 中反序列化 ArrayList(结构错误的 JSON)

标签 java android json jackson gson

大家好,我遇到了来自客户端服务器的一些错误 JSON 结构的问题,我的客户端无法更改,并且我在这一侧有句柄。

我正在从 JSON 创建 POJO,并且已经尝试过使用 GSON,现在我正在使用 JACKSON,因为我认为 JACKSON TREE 会帮助我。

问题是服务器在只有一个对象时返回一个对象(扩展名),在有多个对象时返回一个 ArrayList。我知道这是一个糟糕的结构,为什么不返回一个包含 1 个对象的数组,但我无能为力。

在我的 POJO 类中,我希望始终获得一个 ArrayList,换句话说,如果它只是向数组中添加一个,否则什么都不做。

JSON 示例:

    {
  "result": {
    "FeatureCollection": {
      "boundedBy": {
        "Envelope": {
          "lowerCorner": "-DUMMIE",
          "srsName": "DUMMIE",
          "upperCorner": "DUMMIE"
        }
      },
      "featureMember": [
        {
          "Spill": {
            "DUMMIE": "DUMMIE",
            "DUMMIE": "DUMMIE",
            "DUMMIE": "DUMMIE",
            "extension": {
              "Extension": {
                "area": 401994.1,
                "width": 288.6,
                "DUMMIE": "DUMMIE",
                "length": 2797,
              }
            },
            "DUMMIE": "DUMMIE",
            "DUMMIE": "DUMMIE",
          }
        },
        {
          "Spill": {
            "DUMMIE": "DUMMIE",
            "DUMMIE": "DUMMIE",
            "DUMMIE": "DUMMIE",
            "extension": [
              {
                "Extension": {
                  "area": 401994.1,
                  "width": 288.6,
                  "DUMMIE": "DUMMIE",
                  "length": 2797,
                }
              },
              {
                "Extension": {
                  "area": 401994.1,
                  "width": 288.6,
                  "DUMMIE": "DUMMIE",
                  "length": 2797,
                }
              }
            ],
            "DUMMIE": "DUMMIE",
            "DUMMIE": "DUMMIE",
          }
        }
      ],
      "xsi:schemaLocation": "DUMMIE",
      "numberOfFeatures": 10
    }
  },
  "status": "success"
}

出现问题的 POJO 类

public class Spill {

@JsonProperty("dataSource")
private String dataSource;
@JsonProperty("timeStamp")
private String timeStamp;
@JsonProperty("SARWind_windIntensity")
private Double SARWindWindIntensity;
@JsonProperty("reliabilityIndex")
private Double reliabilityIndex;
@JsonProperty("meteoWind_dataType")
private String meteoWindDataType;
@JsonProperty("eventid")
private String eventid;
@JsonProperty("center")
private Center center;
@JsonProperty("area")
private Double area;
@JsonProperty("description")
private String description;
@JsonProperty("SARWind_windDirection")
private Long SARWindWindDirection;
@JsonProperty("name")
private String name;
@JsonProperty("meteoWind_dataSource")
private String meteoWindDataSource;
@JsonProperty("length")
private Double length;
@JsonProperty("meteoWind_windIntensity")
private Double meteoWindWindIntensity;
@JsonProperty("SARWind_dataSource")
private String SARWindDataSource;
@JsonProperty("SARWind_dataType")
private String SARWindDataType;
@JsonProperty("meteoWind_windDirection")
private Long meteoWindWindDirection;
@JsonProperty("imageIdentifier")
private ImageIdentifier imageIdentifier;
@JsonProperty("width")
private Double width;
@JsonProperty("origin")
private String origin;
@JsonProperty("extension")
private List<Extension> extension = new ArrayList<Extension>();
@JsonProperty("boundedBy")
private BoundedBy__ boundedBy;
@JsonProperty("auxiliaryDataRef")
private AuxiliaryDataRef auxiliaryDataRef;
@JsonProperty("gml:id")
private String gmlId;
@JsonProperty("alignedWithTrack")
private Boolean alignedWithTrack;
@JsonProperty("distanceFromCoast")
private Long distanceFromCoast;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

/**
 * 
 * @return The dataSource
 */
@JsonProperty("dataSource")
public String getDataSource() {
    return dataSource;
}

/**
 * 
 * @param dataSource
 *            The dataSource
 */
@JsonProperty("dataSource")
public void setDataSource(String dataSource) {
    this.dataSource = dataSource;
}

/**
 * 
 * @return The timeStamp
 */
@JsonProperty("timeStamp")
public String getTimeStamp() {
    return timeStamp;
}

/**
 * 
 * @param timeStamp
 *            The timeStamp
 */
@JsonProperty("timeStamp")
public void setTimeStamp(String timeStamp) {
    this.timeStamp = timeStamp;
}

/**
 * 
 * @return The SARWindWindIntensity
 */
@JsonProperty("SARWind_windIntensity")
public Double getSARWindWindIntensity() {
    return SARWindWindIntensity;
}

/**
 * 
 * @param SARWindWindIntensity
 *            The SARWind_windIntensity
 */
@JsonProperty("SARWind_windIntensity")
public void setSARWindWindIntensity(Double SARWindWindIntensity) {
    this.SARWindWindIntensity = SARWindWindIntensity;
}

/**
 * 
 * @return The reliabilityIndex
 */
@JsonProperty("reliabilityIndex")
public Double getReliabilityIndex() {
    return reliabilityIndex;
}

/**
 * 
 * @param reliabilityIndex
 *            The reliabilityIndex
 */
@JsonProperty("reliabilityIndex")
public void setReliabilityIndex(Double reliabilityIndex) {
    this.reliabilityIndex = reliabilityIndex;
}

/**
 * 
 * @return The meteoWindDataType
 */
@JsonProperty("meteoWind_dataType")
public String getMeteoWindDataType() {
    return meteoWindDataType;
}

/**
 * 
 * @param meteoWindDataType
 *            The meteoWind_dataType
 */
@JsonProperty("meteoWind_dataType")
public void setMeteoWindDataType(String meteoWindDataType) {
    this.meteoWindDataType = meteoWindDataType;
}

/**
 * 
 * @return The eventid
 */
@JsonProperty("eventid")
public String getEventid() {
    return eventid;
}

/**
 * 
 * @param eventid
 *            The eventid
 */
@JsonProperty("eventid")
public void setEventid(String eventid) {
    this.eventid = eventid;
}

/**
 * 
 * @return The center
 */
@JsonProperty("center")
public Center getCenter() {
    return center;
}

/**
 * 
 * @param center
 *            The center
 */
@JsonProperty("center")
public void setCenter(Center center) {
    this.center = center;
}

/**
 * 
 * @return The area
 */
@JsonProperty("area")
public Double getArea() {
    return area;
}

/**
 * 
 * @param area
 *            The area
 */
@JsonProperty("area")
public void setArea(Double area) {
    this.area = area;
}

/**
 * 
 * @return The description
 */
@JsonProperty("description")
public String getDescription() {
    return description;
}

/**
 * 
 * @param description
 *            The description
 */
@JsonProperty("description")
public void setDescription(String description) {
    this.description = description;
}

/**
 * 
 * @return The SARWindWindDirection
 */
@JsonProperty("SARWind_windDirection")
public Long getSARWindWindDirection() {
    return SARWindWindDirection;
}

/**
 * 
 * @param SARWindWindDirection
 *            The SARWind_windDirection
 */
@JsonProperty("SARWind_windDirection")
public void setSARWindWindDirection(Long SARWindWindDirection) {
    this.SARWindWindDirection = SARWindWindDirection;
}

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

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

/**
 * 
 * @return The meteoWindDataSource
 */
@JsonProperty("meteoWind_dataSource")
public String getMeteoWindDataSource() {
    return meteoWindDataSource;
}

/**
 * 
 * @param meteoWindDataSource
 *            The meteoWind_dataSource
 */
@JsonProperty("meteoWind_dataSource")
public void setMeteoWindDataSource(String meteoWindDataSource) {
    this.meteoWindDataSource = meteoWindDataSource;
}

/**
 * 
 * @return The length
 */
@JsonProperty("length")
public Double getLength() {
    return length;
}

/**
 * 
 * @param length
 *            The length
 */
@JsonProperty("length")
public void setLength(Double length) {
    this.length = length;
}

/**
 * 
 * @return The meteoWindWindIntensity
 */
@JsonProperty("meteoWind_windIntensity")
public Double getMeteoWindWindIntensity() {
    return meteoWindWindIntensity;
}

/**
 * 
 * @param meteoWindWindIntensity
 *            The meteoWind_windIntensity
 */
@JsonProperty("meteoWind_windIntensity")
public void setMeteoWindWindIntensity(Double meteoWindWindIntensity) {
    this.meteoWindWindIntensity = meteoWindWindIntensity;
}

/**
 * 
 * @return The SARWindDataSource
 */
@JsonProperty("SARWind_dataSource")
public String getSARWindDataSource() {
    return SARWindDataSource;
}

/**
 * 
 * @param SARWindDataSource
 *            The SARWind_dataSource
 */
@JsonProperty("SARWind_dataSource")
public void setSARWindDataSource(String SARWindDataSource) {
    this.SARWindDataSource = SARWindDataSource;
}

/**
 * 
 * @return The SARWindDataType
 */
@JsonProperty("SARWind_dataType")
public String getSARWindDataType() {
    return SARWindDataType;
}

/**
 * 
 * @param SARWindDataType
 *            The SARWind_dataType
 */
@JsonProperty("SARWind_dataType")
public void setSARWindDataType(String SARWindDataType) {
    this.SARWindDataType = SARWindDataType;
}

/**
 * 
 * @return The meteoWindWindDirection
 */
@JsonProperty("meteoWind_windDirection")
public Long getMeteoWindWindDirection() {
    return meteoWindWindDirection;
}

/**
 * 
 * @param meteoWindWindDirection
 *            The meteoWind_windDirection
 */
@JsonProperty("meteoWind_windDirection")
public void setMeteoWindWindDirection(Long meteoWindWindDirection) {
    this.meteoWindWindDirection = meteoWindWindDirection;
}

/**
 * 
 * @return The imageIdentifier
 */
@JsonProperty("imageIdentifier")
public ImageIdentifier getImageIdentifier() {
    return imageIdentifier;
}

/**
 * 
 * @param imageIdentifier
 *            The imageIdentifier
 */
@JsonProperty("imageIdentifier")
public void setImageIdentifier(ImageIdentifier imageIdentifier) {
    this.imageIdentifier = imageIdentifier;
}

/**
 * 
 * @return The width
 */
@JsonProperty("width")
public Double getWidth() {
    return width;
}

/**
 * 
 * @param width
 *            The width
 */
@JsonProperty("width")
public void setWidth(Double width) {
    this.width = width;
}

/**
 * 
 * @return The origin
 */
@JsonProperty("origin")
public String getOrigin() {
    return origin;
}

/**
 * 
 * @param origin
 *            The origin
 */
@JsonProperty("origin")
public void setOrigin(String origin) {
    this.origin = origin;
}

/**
 * 
 * @return The extension
 */
@JsonProperty("extension")
public List<Extension> getExtension() {
    return extension;
}

/**
 * 
 * @param extension
 *            The extension
 */
@JsonProperty("extension")
public void setExtension(List<Extension> extension) {
    this.extension = extension;
}

/**
 * 
 * @return The boundedBy
 */
@JsonProperty("boundedBy")
public BoundedBy__ getBoundedBy() {
    return boundedBy;
}

/**
 * 
 * @param boundedBy
 *            The boundedBy
 */
@JsonProperty("boundedBy")
public void setBoundedBy(BoundedBy__ boundedBy) {
    this.boundedBy = boundedBy;
}

/**
 * 
 * @return The auxiliaryDataRef
 */
@JsonProperty("auxiliaryDataRef")
public AuxiliaryDataRef getAuxiliaryDataRef() {
    return auxiliaryDataRef;
}

/**
 * 
 * @param auxiliaryDataRef
 *            The auxiliaryDataRef
 */
@JsonProperty("auxiliaryDataRef")
public void setAuxiliaryDataRef(AuxiliaryDataRef auxiliaryDataRef) {
    this.auxiliaryDataRef = auxiliaryDataRef;
}

/**
 * 
 * @return The gmlId
 */
@JsonProperty("gml:id")
public String getGmlId() {
    return gmlId;
}

/**
 * 
 * @param gmlId
 *            The gml:id
 */
@JsonProperty("gml:id")
public void setGmlId(String gmlId) {
    this.gmlId = gmlId;
}

/**
 * 
 * @return The alignedWithTrack
 */
@JsonProperty("alignedWithTrack")
public Boolean getAlignedWithTrack() {
    return alignedWithTrack;
}

/**
 * 
 * @param alignedWithTrack
 *            The alignedWithTrack
 */
@JsonProperty("alignedWithTrack")
public void setAlignedWithTrack(Boolean alignedWithTrack) {
    this.alignedWithTrack = alignedWithTrack;
}

/**
 * 
 * @return The distanceFromCoast
 */
@JsonProperty("distanceFromCoast")
public Long getDistanceFromCoast() {
    return distanceFromCoast;
}

/**
 * 
 * @param distanceFromCoast
 *            The distanceFromCoast
 */
@JsonProperty("distanceFromCoast")
public void setDistanceFromCoast(Long distanceFromCoast) {
    this.distanceFromCoast = distanceFromCoast;
}

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

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

}

我尝试过的: GSON:

CnsDetection cnsDetection = gson.fromJson(json, CnsDetection.class);

jackson

    ObjectMapper mapper = new ObjectMapper();
cnsDetection = mapper.readValue(json, CnsDetection.class);

尝试使用自定义反序列化器,但没有成功。 我的主要问题是如何将特定节点从对象更改为 arrayList,然后如何创建包含 Spill 对象的 CnsDetection 对象。

我还读过: -How to dynamically handle json response array/object using Gson -GSON Expected BEGIN_ARRAY but was BEGIN_OBJECT

更新

我已经尝试过@vzamanillo 的答案,但遇到了几个错误,但这个答案让我走上了正确的道路,并为我的问题提供了正确的答案。 PS:正如他在这里询问的那样,这是我的 ExtensionDeserializer:

注意: jacksonHelper 它是一个单例,因此我可以在应用程序中重用映射器。

解串器不工作

public class ExtensionDeserializer extends JsonDeserializer<List<Extension>> {
JacksonHelper jacksonHelper = JacksonHelper.getInstance();

@Override
public List<Extension> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    List<Extension> result = new ArrayList<Extension>();

    if (node.isObject()) {
        result =
                jacksonHelper.getMapper().convertValue(node,
                        jacksonHelper.getMapper().getTypeFactory().constructCollectionType(List.class, Extension.class));
    }
    if (node.isArray()) {
        result.add(jsonParser.readValueAs(Extension.class));
    }
    return result;
}}

正在运行的反序列化器归功于:@vzamanillo

public class ExtensionDeserializer extends JsonDeserializer<List<Extension>> {
JacksonHelper jacksonHelper = JacksonHelper.getInstance();

@Override
public List<Extension> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    ObjectCodec oc = jsonParser.getCodec();
    JsonNode node = oc.readTree(jsonParser);
    List<Extension> result = new ArrayList<Extension>();

    if (node.isObject()) {
        result.add(jacksonHelper.getMapper().treeToValue(node, Extension.class));
    }
    if (node.isArray()) {
        result = jacksonHelper.getMapper().readValue(node.traverse(), new TypeReference<List<Extension>>() {
        });
    }
    return result;
}}

最佳答案

extension属性创建一个自定义的JsonDeserializer,并检查节点类型是数组还是对象,如果节点是对象,则将其添加到返回的List中。

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

    import org.codehaus.jackson.JsonNode;
    import org.codehaus.jackson.JsonParser;
    import org.codehaus.jackson.ObjectCodec;
    import org.codehaus.jackson.map.DeserializationContext;
    import org.codehaus.jackson.map.JsonDeserializer;
    import org.codehaus.jackson.map.ObjectMapper;

    class ExtensionDeSerializer extends JsonDeserializer<List<Extension>> {
        @Override
        public List<Extension> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
            ObjectCodec oc = jsonParser.getCodec();
            JsonNode node = oc.readTree(jsonParser);
            List<Extension> result = new ArrayList<Extension>();
            if (node.isObject()) {

                ObjectMapper mapper = new ObjectMapper();
                // @firetrap less obscure and better solution
                //result.add(jacksonHelper.getMapper().treeToValue(node, Extension.class));

                result = mapper.convertValue(node, mapper.getTypeFactory().constructCollectionType(List.class, Extension.class));
            }
            if (node.isArray()) {
                result.add(jsonParser.readValueAs(Extension.class));
            }
            return result;
        }
    }

@JsonDeserialize 注释添加到 POJO 类中的 extension 属性。

@JsonDeserialize(using=ExtensionDeSerializer.class)
@JsonProperty("extension")
private List<Extension> extension = new ArrayList<Extension>();

当属性可以是对象或数组时,这(可能)是解决问题的最有效方法。

希望这有帮助。

关于java - Android JSON 无法从 START_OBJECT 中反序列化 ArrayList(结构错误的 JSON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30198398/

相关文章:

java - 由于找不到 ALPN 处理器,与 WireMock 的集成测试失败

java - 如何在Struts中使用servlet在JSP中动态检索SQL记录

android - 将毫米转换为像素

javascript - .txt 文件和 .json 文件是否同样适用于存储 javascript 对象?

java - SharedPreferences Android 中奇怪的无法解释的行为

java - 如何理解异步 Web 服务客户端代码中 AsyncHandler 的这种使用,在 Java 中?

android - Eclipse 和 Android SDK 问题 "aapt.exe has stopped"

android - 如何将通知从网站发送到Android应用程序

java - 无法将 JSON 值反序列化为类型

java - 将 .json 文件转换为 JSONArray