search

Home  >  Q&A  >  body text

java - fastjson 或者 Gson 有没有对某个类自定义 json 的办法。

有一个特殊的类型,不希望按照 bean 方式json 化,能不能用自己的方法替换。

PHP中文网PHP中文网2889 days ago364

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 18:03:29

    Solved it myself:

        ObjectSerializer recordFilter = new ObjectSerializer() {
            @Override
            public void write(JSONSerializer jsonSerializer, Object o, Object o1, Type type) throws IOException {
                SerializeWriter out = jsonSerializer.getWriter();
                Record record = (Record) o;
                if( record != null){
                    out.write(record.toJson());
                }else{
                    out.writeNull();
                }
            }
        };
    
        public LocalConductor() {
            SerializeConfig.getGlobalInstance()
                    .put(Record.class, recordFilter);
    
        }

    Interface may change

    Use the put method of the SerializeConfig class to modify the parsing of the specified type.

    reply
    0
  • PHPz

    PHPz2017-04-17 18:03:29

    I don’t understand very well, you can post an example. If you don’t use beans, you can use fastjson’s get method to return the result

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 18:03:29

    JSONSerializer

    reply
    0
  • Cancelreply