使用gson序列化对象图-对象不完整

时间:2019-01-06 11:09:15

标签: java serialization gson

我要序列化对象Bar,其中包含原始类型和HashMap。

public class Bar{
 int simpleValue;
 HashMap<Foo,Integer> map;
...
}

public class Foo{
 ...
}

我使用Gson创建一个Json-String:

Gson gson = new Gson();
String json = gson.toJson(barObject);

这将导致以下字符串:

{"simpleValue":9,"map":{"com.blabla.Foo@2d9b7da":120,...}}

为什么只有对象名称的字符串表示形式?

我在做什么错了?

gson.toJson(fooObject)打印出Foo的正确属性...

1 个答案:

答案 0 :(得分:0)

您的代码正在打印出对象名称的字符串表示形式,因为$app->get('/api/download/content/image/{filename}', function($request, Slim\Http\Response $response, $args) { $file = __DIR__ . '/uploads/content/image/'. $args['filename']; $fh = fopen($file, 'rb'); $stream = new \Slim\Http\Stream($fh); // create a stream instance for the response body return $response->withHeader('Content-Type', 'application/force-download') ->withHeader('Content-Type', 'application/octet-stream') ->withHeader('Content-Type', 'application/download') ->withHeader('Content-Description', 'File Transfer') ->withHeader('Content-Transfer-Encoding', 'binary') ->withHeader('Content-Disposition', 'attachment; filename="' . basename($file) . '"') ->withHeader('Expires', '0') ->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0') ->withHeader('Pragma', 'public') ->withBody($stream); }); 类具有一个Bar对象,且其键为一个类,其关键字Map未被覆盖。
toString()使用gson实现来生成json密钥。
由于尚未实现,因此它会退回到默认的toString()来生成密钥。因此是输出。

以下是演示行为的来源,

Object.toString()

以下的输出是

public class Bar {
    Map<Foo, Integer> map;
    public static void main(String[] args) {
        Gson g = new Gson();
        TracingAspect t = new Bar();
        t.map = new HashMap<>();
        t.map.put(new Foo("ff"), 5);
        String j = g.toJson(t);
        System.out.println(j);
    }

}
class Foo {
    String a;
    public Foo (String a) {this.a=a;}
    @Override
    public String toString () {
        return a;
    }
}
相关问题