使用gson将Java对象转换为JSON字符串 [英] Convert Java objects to JSON strings using gson

查看:402
本文介绍了使用gson将Java对象转换为JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到了一个示例,该示例说明了如何将json转换为java对象,但是在这里我需要将Java对象转换为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

我有一个Java对象,现在我想将Java对象转换为Gson.我该如何实现,请参考我的代码.

I have a Java object and now I want to convert the Java object to Gson. How can I achieve this, please refer my code.

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

我需要将staff对象转换为gson对象

I need to convert staff object to gson object

这是我的员工班级

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

我该怎么办?

推荐答案

首先:没有"gson"对象.仅存在JSON数据,特定格式的字符串,而Gson工具允许您将JSON字符串转换为Java对象(JSON解析),并将Java对象转换为JSON字符串.从那里开始,您的请求可以归结为:

First of all: there are no "gson" objects. 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. 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.

这篇关于使用gson将Java对象转换为JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆