使用jackson库创建json反斜杠+斜杠

yzxexxkh  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(700)

在java类中有一个字段

String cardExpiration = "1022"; //I can format it as needed

使用jackson libray,我需要创建以下json:

{
  "cardExpiration":"10\/22"
}

我正在使用以下代码

String cardExpiration = "10\\/22";
        MyPojo myPojo = new MyPojo(cardExpiration);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(myPojo);

这段代码返回带有“10\/22”的json(双反斜杠,但我只需要一个反斜杠)。我不能在java中创建字符串“10/22”,因为它在字符串文本中是非法的转义字符。知道如何使用json“10/22”吗?

7kqas0il

7kqas0il1#

用第二个反斜杠转义,将其定义为字符串。

String cardExpiration = "10\\/22";
System.out.println(cardExpiration); // prints 10\/22

下面是一个工作示例,其中包括使用jackson序列化pojo。请注意,jackson在json auto中转义了反斜杠。为你。如果你真的想要json值 {"cardExpiration":10\/22} 您可以向pojo中的属性添加@jsonrawvalue注解。

pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.mycompany.app</groupId>
    <artifactId>my-app</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.11.2</version>
        </dependency>
    </dependencies>
</project>

应用程序.java

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

    public static void main(String[] args) throws JsonProcessingException {
        String cardExpiration = "10\\/22";
        System.out.println(cardExpiration); // prints 10\/22

        MyPojo myPojo = new MyPojo(cardExpiration);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(myPojo);
        System.out.println(json); // prints {"cardExpiration":"10\\/22"}
    }

}

class MyPojo {
    String cardExpiration;

    public MyPojo(String cardExpiration) {
        this.cardExpiration = cardExpiration;
    }

    public String getCardExpiration() {
        return cardExpiration;
    }

    public void setCardExpiration(String cardExpiration) {
        this.cardExpiration = cardExpiration;
    }
}

相关问题