Using fastjson to deserialize MangoDB query results with numberLong as an example

Posted by rIkLuNd on Mon, 14 Oct 2019 19:37:30 +0200

The data recorded in mangodb is

{ 
    "_id" : ObjectId("5d3ac7a9c7cf3e3da8343961"), 
    "createTime" : NumberLong(1564133289504), 
    "isPopup" : true, 
    "level" : NumberInt(55), 
    "type" : NumberInt(1), 
    "uid" : NumberInt(8)
}

Query data using MongoTemplate

        Document document = new Document();
        document.put("uid",uid);
        document.put("type",type.value);
        FindIterable<Document> findIterable = getCollection().find(document).limit(1);
        MongoCursor<Document> iterator = findIterable.iterator();
        BaseUserPopupInfoModel model = null;
        if (iterator.hasNext()){
            String json = iterator.next().toJson();
            System.out.println(json);
            model = (BaseUserPopupInfoModel)JSON.parseObject(json,type.classType);
        }

Failed to deserialize using fastjson. The output json data printed is

{
  "_id": {
    "$oid": "5d3ac7a9c7cf3e3da8343961"
  },
  "createTime": {
    "$numberLong": "1564133289504"
  },
  "isPopup": true,
  "level": 55,
  "type": 1,
  "uid": 8
}

You can see that the createTime field corresponds not to a timestamp, but to a class. At this point, you need to customize the deserialization tool to extract data.
Because we are using the deserialization of fastjson, we need to customize the deserializer of fastjson.

import com.alibaba.fastjson.parser.DefaultJSONParser;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;
import com.youxiake.utils.StringUtil;
import java.lang.reflect.Type;

public class MongoLongConverter implements ObjectDeserializer {

    @Override
    public Long deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
        String longStr = parser.parseObject().getString("$numberLong");
        if (StringUtil.isNotEmptyOrNull(longStr)){
            return Long.parseLong(longStr);
        }
        return 0L;
    }

    @Override
    public int getFastMatchToken() {
        return 0;
    }
}

Indicate the use of the deserializer on the fields you need to use

    /**
     * Creation time
     */
    @JSONField(deserializeUsing =MongoLongConverter.class )
    private Long createTime;

If Jackson's deserialization is used, you can refer to it.

Topics: Programming JSON Java