Map to JSON string, object to JSON string, JSON. toJSONString()

Author : xuzhiping   2023-03-07 11:17:22 Browse: 728

Abstract: 1.Preface It is unavoidable for us to deal with JSON in the development process, which is not what we have encountered recently. ...

1.Preface

It is unavoidable for us to deal with JSON in the development process, which is not what we have encountered recently. You need to convert some information into JSON strings and save them in the database. There are two ways to think of. One is to create a new entity class, and then convert it to JSON. The small editor is lazy. How sweet it is to map directly! We can only use Alibaba's fastjson to convert directly, which is very convenient!

JSON

2.Ideal transformation display

{"gender": "male", "name": "Xiaoming", "age": "18"}
// empty display
{}

3.Import maven dependency

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.69</version>
</dependency>

4.Map conversion JSON string

Private static String mapToJson () {
Map < String,String > map = new HashMap < >
Map.put ("age", "18")
Map.put ("name", "Xiaoming")
Map.put ("gender", "male")
String string = JSON.toJSONString (map)
System.out.println (string)
Map.clear ()
String stringNull = JSON.toJSONString (map)
System.out.println (stringNull)
Return string
}

5.Object to JSON string

Pojo

Import lombok.Data

@ Data
Public class UserPojo {

Private String name
Private String gender
Private String age

}

Method

Private static String pojoToJson () {

UserPojo userPojo = new UserPojo ()
String stringNull = JSON.toJSONString (userPojo)
System.out.println (stringNull)
UserPojo.setAge ("19")
UserPojo.setGender ("female")
UserPojo.setName ("Xiao Hong")
String string = JSON.toJSONString (userPojo)
System.out.println (string)
Return string

}

6.Summary

That's how it works. Generally speaking, fastjson is very easy to use. However, it is said that fastjson is not safe and there is no jackson security. However, I still think that fastjson is used more and used to the methods in it.

Label :
    Sign in for comments!
Comment list (0)

Powered by TorCMS (https://github.com/bukun/TorCMS).