我想在JavaSE独立应用程序中使用JAXB来读写Json文件。 我设法使用下面的代码片段为XML文件执行此操作,但我不明白如何切换到Json:
public class Main {
public static void main(String[] args) throws Exception {
Book book = new Book();
book.title = "hello";
JAXBContext context = JAXBContext.newInstance(Book.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(book, System.out);
}
}
注意:
答案 0 :(得分:2)
使用EclipseLink MOXy,您可以添加属性来操作输出。
public class Main {
public static void main(String[] args) {
Book book = new Book();
book.title = "hello";
JAXBContext context;
try {
context = JAXBContextFactory.createContext(new Class[] {Book.class}, null);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(MarshallerProperties.MEDIA_TYPE, "application/json");
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(book, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
会导致: { “书”:{ “标题”:“你好” } }
类路径上需要org.eclipse.persistence.moxy-2.5.1.jar和org.eclipse.persistence.core-2.5.1.jar。 在我自己玩这个时,我遇到了:hottest JAXB answers。特别是Blaise Doughan在非常有帮助的地方回答。 搜索
MarshallerProperties.MEDIA_TYPE, "application/json"
更多他的例子。
答案 1 :(得分:0)
如果你愿意,你可以创建一个单独的方法就像这样非常简单(如果你已经有了JAXB库)
主要班级
import java.io.IOException;
import javax.xml.bind.JAXBException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
public class ConvertJson {
public static void main(String[] args) {
final JavaObject javaObject = new JavaObject();
javaObject.setName("Json");
javaObject.setRole("Moderator");
javaObject.setAge(28);
try {
pojo2Json(javaObject);
} catch (JAXBException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static String pojo2Json(Object obj) throws JAXBException,
JsonParseException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(obj);
System.out.print(jsonString);
return jsonString;
}
这是pojo
import org.codehaus.jackson.annotate.JsonProperty;
public class JavaObject{
@JsonProperty(value = "Name")
private String name;
@JsonProperty(value = "Role")
private String role;
@JsonProperty(value = "Age")
private int age;
public JavaObject(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
答案 2 :(得分:0)
你会这样做:
public class Main {
public static void main(String[] args) throws IOException {
Book book = new Book();
book.title = "hello";
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(System.out, book);
}
}