从特定字符串转换为JSON

时间:2013-06-10 20:51:38

标签: java regex json parsing

假设我有这个字符串:

For the AWSDataTransfer product, this is the public pricing plan.

Regarding data transfer across EC2 AZs:
In all AWS regions, inbound is $0.01/GB.
In all AWS regions, outbound is $0.01/GB.

我想把它改成JSON,就像这样:

{
    "Product" : "AWSDataTransfer",
    "PlanName" : "public",

    "EC2Regional" : [
        {"region" : "all", "type" : "in", "rate" : "0.01/GB"},
        {"region" : "all", "type" : "out", "rate" : "0.01/GB"}
    ],
}

如何使用正则表达式执行此操作。任何人都可以编写代码并帮助我。

1 个答案:

答案 0 :(得分:2)

您可以创建一个或两个包含您描述的字段的简单类,例如:

public class Plan {
    private String product;
    private String planName;
    private List<EC2Regional> ec2Regional;
}

public class EC2Regional {
    private String region;
    private String type;
    private String rate;
}

(为了便于阅读,我遗漏了getter和setter。) 然后,您可以使用像Jackson这样的JSON库将其序列化为JSON。

您可能希望用枚举或其他自定义类型替换某些String类型。

祝你好运。