2

fastjson can't correctly transfer complex object or the cast I use is wrong.

I find a question in my project.so write a test like this:

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 */
public class Test {

public static void main(String[] args)  {

    Map<Integer,List<String>> map1 = new HashMap<>();
    List<String> list1 = new ArrayList<>();
    list1.add("555");
    map1.put(5,list1);
    System.out.println(map1.get("5"));
    Pack pack1 = new Pack();
    pack1.setT(1);
    pack1.setInfo(map1);
    String jsonStr1 = JSONObject.toJSONString(pack1);
    Pack pack2 = JSONObject.parseObject(jsonStr1,Pack.class);

    Object ob1 = pack2.getInfo();
    Map<Integer,List<String>> map2 = (Map<Integer, List<String>>)ob1;
    List<String> list2 = map2.get(5);
    System.out.println(list2 == null);

}
static class Pack{
    Integer t;
    Object info;

    public Object getInfo() {
        return info;
    }

    public void setInfo(Object info) {
        this.info = info;
    }


    public Integer getT() {
        return t;
    }


    public void setT(Integer t) {
        this.t = t;
    }
}
}

I can't understand why the list2 is null when the debug shows like the picture the debug info is :

enter image description here

Fanl
  • 1,491
  • 2
  • 11
  • 15
  • Looks like this library just doesn't know how to handle that kind of objects. The JSON produced is malformed. By the way, it would be impossible to correctly convert this object to JSON then reconvert this JSON to equivalent objects. Integer would have to be converted to String at least. – kumesana Jul 18 '18 at 11:55
  • It seems the fastjson need type info in the step: Pack pack2 = JSONObject.parseObject(jsonStr1,Pack.class); Change the 'info' type from Object to Map>, It works corecctly – Fanl Jul 19 '18 at 02:10
  • If it still produces the JSON `{"info":{5:["555"]},"t":1}` then that's not correct. That's malformed JSON. 5 is not a valid property name. "5", with quotes, would be. – kumesana Jul 19 '18 at 14:33

0 Answers0