Solution for missing space fields when fastjson parses generic json strings

The scenario is as follows:

There is a public interface that returns a json string, but the type of object represented by the json string is uncertain, either ClassA or ClassB.

public class ClassA{
   private String key;
   private String value;
   ...
}

public class ClassB{
   private String host;
   private int id;
   private String user;
   private String db;
   ...
}

//情况1:返回ClassA的json字符串
str = {"key":"user", "value":"ming"}
//情况2:返回ClassB的json字符串串
str = {"host":"localhost", "id":1, "user":"ming", "db":null}

In this case, we generally parse the result into a JSONObject object:

JSONObject obj = JSON.praseObject(str);

But using the above method, parse the above JSONObject and pass it to other interfaces (assuming A).
A The received JSONObject may lose some field information, such as the db field in the str above. When printing, the db field is missing.

Therefore, the solution to this situation:

HashMap<String, Object> result = JSON.parseObject(str, 
            new TypeReference<HashMap<String, Object>>(){});
JSONObject obj = JSON.praseObject(JSON.toJSONString(result, 
            SerializerFeature.WriteMapNullValue));

At this time, the parsed JSONObject object is passed to other interfaces. At this time, the object information is complete,
that is, the fields will not be missing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326180695&siteId=291194637