简体   繁体   English

使用gson将Java对象转换为JSON字符串

[英]Convert Java objects to JSON strings using gson

I've found some example here which says how to convert json to java object but here I need to convert Java object to GSON 我在这里找到了一些示例,该示例说明了如何将json转换为java对象,但是在这里我需要将Java对象转换为GSON

I have a Java object and now I want to convert the Java object to Gson. 我有一个Java对象,现在我想将Java对象转换为Gson。 How can I achieve this, please refer my code. 我该如何实现,请参考我的代码。

Staff obj = new Staff();
Gson gson = new Gson();

I need to convert staff object to gson object 我需要将人员对象转换为gson对象

This is my staff class 这是我的职员班

public class Staff {    
    private String name;
    private int age;
    private String position;
    private BigDecimal salary;
    private List<String> skills;

How can I go about this? 我该怎么办?

First of all: there are no "gson" objects. 首先:没有“ gson”对象。 There is just JSON data, strings in a specific format, and the Gson tooling allows you to turn JSON strings into java objects (json parsing), and turning java objects into JSON strings. 仅存在JSON数据,特定格式的字符串,而Gson工具允许您将JSON字符串转换为Java对象(JSON解析),并将Java对象转换为JSON字符串。 Coming from there, your request boils down to: 从那里开始,您的请求可以归结为:

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

Beyond that, you should acquire a good tutorial and study this topic, like this one here . 除此之外,您还应该获得一个不错的教程并学习这个主题,例如这里的主题。

Examples from the API: API中的示例:

 Gson gson = new Gson(); // Or use new GsonBuilder().create();
 MyType target = new MyType();
 String json = gson.toJson(target); // serializes target to Json
 MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

For lists or parameterized types: 对于列表或参数化类型:

 Type listType = new TypeToken<List<String>>() {}.getType();
 List<String> target = new LinkedList<String>();
 target.add("blah");

 Gson gson = new Gson();
 String json = gson.toJson(target, listType);
 List<String> target2 = gson.fromJson(json, listType);

API docs and link for more examples API文档更多示例的链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM