gpt4 book ai didi

java - 如何使用 JAXB Moxy 解码具有未命名字段的 JSON

转载 作者:行者123 更新时间:2023-11-30 08:17:15 25 4
gpt4 key购买 nike

解码此 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;
}
}

应用程序.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 类在这里是多余的。

所以你可以简单地将该数组解码到列表中。否则你将不得不更改 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();

关于java - 如何使用 JAXB Moxy 解码具有未命名字段的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29483922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com