所以我用杰克逊JSON序列化/反序列化成功地uptil现在,现在我也在努力将其用于XML序列化/反序列化使用它jackson-dataformat-xml-2.3.0.jar。
我用过了
objectmapper.reader(Student.class).withRootName("prefix:student").readValue(jsonString)
将我的 JSON(具有带前缀的根名称)反序列化为Student成功运行的类。
现在,我试图将我的 XML 字符串(具有带前缀的根名称)反序列化为Student:
XML:
<prefix:student>
<name>
Jack Jones
</name>
<id>1</id>
</prefix:student>
Run Code Online (Sandbox Code Playgroud)
我的POJO:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"name",
"id",
....
})
@XmlRootElement(name = "student")
public class Student
{
protected String name;
BigInteger id;
..........................
}
Run Code Online (Sandbox Code Playgroud)
我desrializing此使用XmlMapper的jackson-dataformat-xml是这样的:
xmlMapper.reader(Student.class).withRootName("prefix:student").readValue(xmlString)
Run Code Online (Sandbox Code Playgroud)
我收到以下异常:
java.io.IOException: com.ctc.wstx.exc.WstxParsingException: Undeclared namespace prefix "prefix"
at [row,col {unknown-source}]: [1,9]
at com.fasterxml.jackson.dataformat.xml.util.StaxUtil.throwXmlAsIOException(StaxUtil.java:24)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:473)
at com.fasterxml.jackson.dataformat.xml.XmlFactory._createParser(XmlFactory.java:26)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:844)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2091)
Caused …Run Code Online (Sandbox Code Playgroud) @JsonIgnoreProperties(ignoreUnknown=false) 不适用于 spring 4.2.0 和更高版本的 spring。但它适用于 4.0.4 和 4.0.1 。我正在使用 spring 4.2.8 并使用 Jackson 依赖项
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.3</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
如果我发送带有无效字段的 json 请求,那么它会作为有效请求接受。但它应该给出错误的请求作为响应。例如:如果我有课
public class Student{
private String id;
private String name;
}
Run Code Online (Sandbox Code Playgroud)
如果发送有效的相应 json 请求,它应该是这样的
{
"id": "123",
"name": "test"
}
Run Code Online (Sandbox Code Playgroud)
但即使我发送带有无效字段的 json 请求,如下所示,它仍然接受。
{
"id": "123",
"name": "test",
"anyinvalidkey": "test"
}
Run Code Online (Sandbox Code Playgroud)
但它应该给出错误的请求作为响应
我使用以下代码将我的源XML转换为JSON.但是,此代码会删除源XML中多次出现的子记录,并且输出JSON仅包含最后一个子记录.
如何将Jackson XML转换为JSON转换器以输出JSON中的所有子记录?
码
XmlMapper xmlMapper = new XmlMapper();
Map entries = xmlMapper.readValue(new File("source.xml"), LinkedHashMap.class);
ObjectMapper jsonMapper = new ObjectMapper();
String json = jsonMapper.writer().writeValueAsString(entries);
System.out.println(json);
Run Code Online (Sandbox Code Playgroud)
源XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<File>
<NumLeases>1</NumLeases>
<FLAG>SUCCESS</FLAG>
<MESSAGE>Test Upload</MESSAGE>
<Lease>
<LeaseVersion>1</LeaseVersion>
<F1501B>
<NEDOCO>18738</NEDOCO>
<NWUNIT>0004</NWUNIT>
<NTRUSTRECORDKEY>12</NTRUSTRECORDKEY>
</F1501B>
<F1501B>
<NEDOCO>18739</NEDOCO>
<NWUNIT>0005</NWUNIT>
<NTRUSTRECORDKEY>8</NTRUSTRECORDKEY>
</F1501B>
</Lease>
</File>
Run Code Online (Sandbox Code Playgroud)
实际产出
{
"NumLeases": "1",
"FLAG": "SUCCESS",
"MESSAGE": "Test Upload",
"Lease": {
"LeaseVersion": "1",
"F1501B": {
"NEDOCO": "18739",
"NWUNIT": "0005",
"NTRUSTRECORDKEY": "8"
}
}
}
Run Code Online (Sandbox Code Playgroud)
预期产出
{
"NumLeases": "1",
"FLAG": "SUCCESS",
"MESSAGE": "Test …Run Code Online (Sandbox Code Playgroud) 有人可以帮忙吗?我被困在读取一个csv文件并将其序列化到POJO上。我正在使用杰克逊图书馆的CsvMapper。读取和序列化部分已完成并且工作正常。问题是,当用户移动标题/列时,导致序列化做出一些字母顺序的假设,即CSV文件上的值也是字母顺序的。
例如(下面的文件在第一行具有标题,第二行具有人员详细信息值)
personNameHeader,personAgeHeader
Wiliam,32
现在我的POJO如下
@JsonIgnoreProperties(ignoreUnknown = true)
// @JsonPropertyOrder(value = {"personNameHeader", "personAgeHeader" })
public class PersonDetailsCSVTemplate {
@JsonProperty("personNameHeader")
private String name;
@JsonProperty("personAgeHeader")
private String age;
//Public constructor and getters and setters...
Run Code Online (Sandbox Code Playgroud)
这是从CSV读取值并将其映射到类的代码
import com.fasterxml.jackson.databind.MappingIterator;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
...
CsvMapper csvMapper = new CsvMapper();
CsvSchema schema = csvMapper.typedSchemaFor(PersonDetailsCSVTemplate.class).withHeader();
MappingIterator<PersonDetailsCSVTemplate > dataIterator = csvMapper.readerFor(PersonDetailsCSVTemplate.class).with(schema)
.readValues(data);
while (dataIterator.hasNextValue()) {
PersonDetailsCSVTemplate dataCSV = dataIterator.nextValue();
}
Run Code Online (Sandbox Code Playgroud)
序列化之后,可以看出CsvMapper映射了以下内容:
PersonDetailsCSVTemplate.name = "32"和PersonDetailsCSVTemplate.age = "Wiliam"
通过用注释类来@JsonPropertyOrder(value = {"personNameHeader", "personAgeHeader" })强制CSV始终是name列,然后是age列,这是不理想的。
任何人都可以提出他们认为可行的建议吗?问候
我想在每次请求日期时使用 DateTimeFormat.ISO.DATE 来配置 Jackson,例如:
@RequestMapping(value = "income")
public ResponseEntity calculateIncome(
@RequestParam(value = "companyName") String companyName,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@RequestParam(value = "startDate") LocalDate startDate,
@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
@RequestParam(value = "endDate") LocalDate endDate
)
Run Code Online (Sandbox Code Playgroud)
我已经尝试在 JacksonConfig 中设置它
mapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Run Code Online (Sandbox Code Playgroud)
或者
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
Run Code Online (Sandbox Code Playgroud)
还
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
Run Code Online (Sandbox Code Playgroud)
或者
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
Run Code Online (Sandbox Code Playgroud)
即使在 application.properties 我试过
spring.jackson.serialization.write_dates_as_timestamps=true
Run Code Online (Sandbox Code Playgroud)
我正在使用具有以下依赖项的 spring-boot
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.5.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson.version}</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我只是不想一遍又一遍地重复相同的 @DataTimeFormat 但没有它,我仍然收到错误:
在 IntelJ
2018-03-01 15:35:05.539 WARN 8168 --- [nio-8080-exec-1] .wsmsDefaultHandlerExceptionResolver:无法绑定请求元素:org.springframework.web.method.annotation.MethodArgumentTypeMismatchException:无法转换值输入'java.lang.String' 到所需的类型'java.time.LocalDate';嵌套异常是 org.springframework.core.convert.ConversionFailedException:无法从类型 [java.lang.String] 转换为类型 [@org.springframework.web.bind.annotation.RequestParam java.time.LocalDate] 的值 '2018 …
我有一个使用 JSON 作为交换数据格式的工作 Spring Boot 应用程序。现在我不得不添加一个仅以 xml 格式发送数据的服务。我添加jackson-dataformat-xml到我的 pom 中,它工作得很好。
@Service
public class TemplateService {
private final RestTemplate restTemplate;
private final String serviceUri;
public TemplateService (RestTemplate restTemplate, @Value("${service.url_templates}") String serviceUri) {
this.restTemplate = restTemplate;
this.serviceUri = serviceUri;
}
public boolean createTemplate(Template template) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
headers.setContentType(MediaType.APPLICATION_XML);
HttpEntity entity = new HttpEntity<>(template, headers);
ResponseEntity<Template> response = restTemplate.exchange(serviceUri, HttpMethod.POST, entity, Template.class);
if (response.getStatusCode().is2xxSuccessful()) {
// do some stuff
return true;
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
现在不幸的是,在添加依赖项后,我所有其他 …
如何使用 Jackson 将 Java 转换Map为 XML?
版本:
'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.8'
Run Code Online (Sandbox Code Playgroud)
代码:
'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.8'
Run Code Online (Sandbox Code Playgroud)
实际输出:
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
public class MainApp {
public static void main(String[] args) throws JsonProcessingException {
Map<String, Object> map = new HashMap<String, Object>();
map.put("key1", "value1");
map.put("key2", "value2");
Application app = new Application();
app.setEntry(map);
// xml output format
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
System.out.println(xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(app));
}
@JacksonXmlRootElement(localName = "headers")
public static class Application {
private Map<String, Object> entry;
public Map<String, Object> getEntry() {
return Collections.unmodifiableMap(entry);
}
public void setEntry(Map<String, …Run Code Online (Sandbox Code Playgroud) 我有一个应用程序,我需要在根级别使用不同的标签序列化 XML。
我使用以下场景实现了一个测试用例,通过相同的输入我得到了两个 xml。
<ClassTypeA>
<fieldA>a</fieldA>
</ClassTypeA>
Run Code Online (Sandbox Code Playgroud)
和
<ClassTypeB>
<fieldB>b</fieldB>
</ClassTypeB>
Run Code Online (Sandbox Code Playgroud)
为了序列化,我实现了这三个类:
<ClassTypeA>
<fieldA>a</fieldA>
</ClassTypeA>
Run Code Online (Sandbox Code Playgroud)
在下面使用此测试会返回以下错误:
<ClassTypeB>
<fieldB>b</fieldB>
</ClassTypeB>
Run Code Online (Sandbox Code Playgroud)
com.fasterxml.jackson.databind.exc.InvalidTypeIdException: Could not resolve type id 'fieldA' as a subtype of `br.com.eletra.filemode.uaa.converter.TestXml`: known type ids = [ClassTypeA, ClassTypeB]
at [Source: (StringReader); line: 2, column: 2]
Run Code Online (Sandbox Code Playgroud)
但是,在结构的开头插入任何标签时,序列化是成功的。
我用演绎类型的jackson 2.12做了另一个测试。
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({
@JsonSubTypes.Type(value = TestConcreteDisconnectXML.class, name = "ClassTypeA"),
@JsonSubTypes.Type(value = TestConcreteConnectXML.class, name = "ClassTypeB"),
})
abstract class TestXml{
}
@Getter
@Setter
class TestConcreteDisconnectXML extends TestXml{
private String fieldA; …Run Code Online (Sandbox Code Playgroud) 我需要帮助jackson-dataformat-xml。我需要将List<String>using序列化XmlMapper到 xml 中,并对引号"\xe2\x86\x92进行编码"。
但是在序列化XmlMapper对所有其他特殊符号(<、等)进行编码后,但完全忽略引号(和)...如果我在序列化之前手动>编码字符串,内容会变得混乱,因为里面有并且它的序列化不是当然。&\'""\'&\'&quot;
也许有人知道如何让它发挥作用?\n另外,有没有一种解决方法可以List<String>使用@JacksonRawValue或类似的方法在字段上禁用自动特殊符号编码?此注释在简单(非数组)字段上效果很好,但在List<String>.
谢谢。
\n我正在使用 jackson 库,并且遇到了一种情况,我想在序列化/反序列化时使用 objectmapper 禁用 @JsonFormat 注释。
我的 Api 代码位于第 3 方库中,因此我无法删除/添加任何注释,因此 objectMapper 是唯一的选择。
API类:
public class ApiClass {
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss'Z'")
private DateTime time;
}
Run Code Online (Sandbox Code Playgroud)
我的代码:
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.configure(Feature.ALLOW_COMMENTS, true);
objectMapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
objectMapper.setSerializationInclusion(Include.NON_ABSENT);
objectMapper.registerModule(new JodaModule());
objectMapper.registerModule(new JavaTimeModule());
String str = " {\"time\": \"2012-05-01\"}";
ApiClass msg = objectMapper.readValue(str, ApiClass.class);
Run Code Online (Sandbox Code Playgroud)
我希望这次转换能够成功进行。
目前我得到: com.fasterxml.jackson.databind.JsonMappingException:格式无效:“2012-05-01”太短
请在这里帮助我。
提前致谢
java jackson jackson-dataformat-xml jackson2 jackson-databind