简体   繁体   English

从普通字符串转换为json字符串,然后转换为bean

[英]Convert from normal string to json string and then to bean

I have the following string 我有以下字符串

    String new_value=
   {
        product_type_id: 1,
        product_cat_id: 1,
        product_type_nm: PED
    }, {
        product_type_id: 2,
        product_cat_id: 2,
        product_type_nm: MOBILE APP
    }, {
        product_type_id: 3,
        product_cat_id: 1,
        product_type_nm: MOBILE
    }, {
        product_type_id: 4,
        product_cat_id: 3,
        product_type_nm: PAYMENT
    }, {
        product_type_id: 5,
        product_cat_id: 5,
        product_type_nm: USER
    }, {
        product_type_id: 6,
        product_cat_id: 6,
        product_type_nm: SMS
    }, {
        product_type_id: 9,
        product_cat_id: 6,
        product_type_nm: EMAIL
    }, {
        product_type_id: 10,
        product_cat_id: 6,
        product_type_nm: TOPUP
    }

This String contains data related to many beans. 此字符串包含与许多bean相关的数据。 I want to convert it into json string and then into bean in java.How can i do it? 我想将其转换为json字符串,然后转换为java中的bean。我该怎么做? I am using 我在用

JSONObject jsonObj = new JSONObject(new_value);

Is it possible with this. 这有可能吗?

For that you can use use Jackson to convert Java object to / from JSON 为此,您可以使用Jackson将Java对象转换为JSON或从JSON转换。

ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'vinit'}";
Staff obj = mapper.readValue(jsonInString, Staff.class); //String to Class Object

Before that you need to add jackson-databind lib. 在此之前,您需要添加jackson-databind lib。

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.6.3</version>
</dependency>

you can see more example on click here 您可以点击此处查看更多示例

Look at the below link: 请看下面的链接:

Generate Java class from JSON? 从JSON生成Java类?

They are converting a Json to POJO. 他们正在将Json转换为POJO。 There are multiple tools available online and you can download the same once done.If there are any exceptions, share the trace logs and someone can help. 在线上有多种工具,您可以在完成后下载它们。如果有任何例外,请共享跟踪日志,其他人可以提供帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM