如何使用 JAXB Moxy 使用未命名字段解组 JSON

How to unmarshal JSON with unnamed fields with JAXB Moxy

解组此 json 字符串时:

[
    {
        "id": "123"
    },
    {
        "id": "456"
    }
]

我收到这个错误:

An exception occured while executing the Java class. null: InvocationTargetException: java.util.ArrayList cannot be cast to com.example.Ids

如何使用 Moxy 将上述 JSON 字符串正确解组为 IDs Java 对象?我还想知道如何使用 Jackson(用于 Jersey 响应)来做到这一点。

这些是 类:

Ids.java

package com.example;

import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@XmlAccessorType(XmlAccessType.FIELD)
public class Ids {
    @XmlList
    private List<Id> ids;

    public List<Id> getIds()
    {
        return ids;
    }

    public void setIds(List<Id> ids)
    {
        this.ids = ids;
    }
}

Id.java

package com.example;

import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@XmlAccessorType(XmlAccessType.FIELD)
public class Id {
    private String id;

    public String getId() {
    return id;
    }

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

App.java

package com.example;

import org.eclipse.persistence.jaxb.JAXBContextProperties;
import org.eclipse.persistence.jaxb.MarshallerProperties;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

import org.eclipse.persistence.jaxb.UnmarshallerProperties;

import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import java.util.*;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
import org.eclipse.persistence.jaxb.JAXBContextProperties;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main( String[] args ) throws Exception {
    String resp = "[ {\"id\" : \"123\" }, {\"id\" : \"456\" } ]";
    Map<String, Object> properties = new HashMap<String, Object>(2);
    properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
    properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
    JAXBContext jc = JAXBContext.newInstance(new Class[] {Ids.class}, properties);

    Unmarshaller unmarshaller = jc.createUnmarshaller();
    StringReader reader = new StringReader(resp);

    StreamSource json = new StreamSource(reader);
    Ids foo = unmarshaller.unmarshal(json, Ids.class).getValue();
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(foo, System.out);
    }
}

我不知道地下。但在我看来,Ids class 在这里是多余的。

所以您可以简单地将数组解组到列表中。否则您将不得不更改 JSON。

如果没有 ID,它将看起来像:

    JAXBContext jc = JAXBContext.newInstance(new Class[]{Id.class}, properties);
    Unmarshaller um = jc.createUnmarshaller();
    StringReader reader = new StringReader(resp);
    List<Id> ids = (List<Id>)um.unmarshal(new StreamSource(reader), Id.class).getValue();