使用JAXB批注将字符串实例变量转换为JSON

时间:2015-10-30 18:20:38

标签: java json jaxb

我有一个带有json格式的String实例变量的对象。

package json;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Test {

    private String json; // Contains a json String {"test": 1}

    public String getJson() {
        return json;
    }
    public void setJson(String json) {
        this.json = json;
    }

}

当我整理这个对象时,我得到以下json:

{
   "json" : "{\"test\": 1}"
}

我想要的是:

{
    "json" : {
        "test" : 1
    }
}

是否有允许这样做的注释?

这是示例代码:

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.eclipse.persistence.jaxb.MarshallerProperties;

public class Main {

  public static void main (String [] args) throws JAXBException {

    JAXBContext context = JAXBContext.newInstance(Test.class);  

    Marshaller m = context.createMarshaller();
    m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);  
    m.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
    m.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, false);


    Test t = new Test();
    t.setJson("{\"test\": 1}");

    m.marshal(t, System.out);  
  }
}

0 个答案:

没有答案