Java 如何将字段为jsonstring的对象转换为JSON

Java 如何将字段为jsonstring的对象转换为JSON,java,gson,Java,Gson,我拥有以下实体: class A { String errors ;// a json string of some type (type could vary). Double value; ... public A(String theErrors, Double theValue) { errors = theErrors; value=theValue; } } A a = new A("{tl:[\"err1\"]..

我拥有以下实体:

class A {
    String errors ;//  a json string of some type (type could vary).
    Double value;
    ...
    public A(String theErrors, Double theValue) {
      errors = theErrors;
      value=theValue;
    }
}

A a = new A("{tl:[\"err1\"]...}", 10d);
我需要将a转换为json字符串

有了谷歌图书馆,我可以使用:

String str = gson.toJson(a)
但是s.a.errors字段是一个字符串,它被转义,结果是:

//{“errors”:“{tl:[“err1”]…}”,“value”:10}

不是

//{“错误”:{tl:[“err1”]…},“值”:10}

至于现在,我试着做一些类似的事情:

String str = gson.toJson(a).replace("\"{", "{").replace("}\"}", "}}")
但这是一个脆弱的解决方案

有谁知道,有没有更好的方法来解决这个问题?提前谢谢


PS:重点是底层错误对象的类型未知(取决于错误的来源)

似乎我找到了解决方案:

String getAsJson(A a) {
    JsonObject jsonMedia = (JsonObject) g.toJsonTree(a);
    jsonMedia.add("errors", g.fromJson(a.getA(), JsonElement.class));
    return g.toJson(jsonMedia);
}

向我们展示构造函数
A(String,Double)
的代码。问题是,在您的代码示例中,第一个参数无效json如果添加
Gson errors\u json在类属性中,在
gson.toString()之前
run
a.errors\u json=gson.toJson(a.errors)