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

时间:2015-04-07 04:44:44

标签: java jaxb jersey jackson moxy

在解组这个json字符串的同时:

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

我收到此错误:

  

执行Java类时发生异常。空值:   InvocationTargetException:java.util.ArrayList无法强制转换为   com.example.Ids

如何使用Moxy将上述JSON字符串正确解组为Ids Java对象?我还想知道如何使用杰克逊(泽西回应)。

这些是类:

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

1 个答案:

答案 0 :(得分:1)

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

所以你可以简单地将该数组解组到List中。或者你必须改变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();