This is the 7th day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Writing in the front

In daily development, we often need to convert strings into collections or objects, or related objects or collections into a Json string, etc.

We usually use one of Alibaba’s open source components, fastjson, which many developers love despite some security issues before version 1.2.7 last year.

Today we will learn how to solve these situations and share relevant knowledge with you.

Fastjson common methods

Convert Map to Json string

To do this, we need to use the JSONObject class in FastJSON, using its internal toJSONString method, which can be used to convert the Map into the corresponding string, see the following code, and the result:

Code examples:

public static void main(String[] args) {
    Map<String,String> map = new HashMap<>();
    map.put("1"."1");
    String json = JSONObject.toJSONString(map);
    System.out.println(json);
}
Copy the code

Running results:

{" 1 ":" 1 "}Copy the code

Convert a List to a JSON string

ToJSONString (Object obj), which I won’t elaborate on here.

String json = JSONObject.toJSONString(map);
Copy the code

ToJSONString method of JSONObject

If you can’t find the toJsonString method in the JsonObject class, don’t panic. The toJsonString method is not unique to the JsonObject class, but is derived from the json. Java class. You should search under the JSON class.

JSON string is converted to Map collection object

Sometimes that’s the way it goes, back and forth, but that’s okay, we already have a solution for that. Take a look.

public static void main(String[] args) {
    String json = "{"1":"1"}";
    Map map = JSON.parseObject(json, Map.class);
}
Copy the code

JSON string to List object

I don’t have to say this, just give me a line of code, feel it yourself.

List list = JSON.parseObject(json, List.class);
Copy the code

JSON string into entity-like object

And we’ll use that as well, so let’s take a look at it.

User user = JSON.parseObject(json, User.class);
Copy the code