Convert java Object into Json String

时间:2015-12-14 17:59:39

标签: java json gson

I have a java class Object:

class TempClass {
@Expose
String errorCode
@Expose
String message
String name
String cause

TempClass(String errorCode, String message) {
    this.errorCode = errorCode
    this.message = message
  }
}

I am able to convert object into json using GSON jar

TempClass t = new TempClass("404","page not found")
GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
String json = builder.create().toJson(t);

The JSON String I am getting is

{ errorCode: "404", message: "page not found" }

But What I want is:

"TempClass"{ errorCode: "404", message: "page not found" }

Or Better if there is any other sophisticated way where I can map "tempClass" (or any other property) into something else.

1 个答案:

答案 0 :(得分:0)

您可以尝试创建一个地图,其中" tempClass"是关键,你的TempClass对象是值,如下所示:

app.post('/licenses', function (req, res) {

    console.log(req.body.expirationDate);
    License.create({

        name: req.body.licenseName,
        licensetype: req.body.licenseType,
        activationcount: 0,
        expirationdate: req.body.expirationDate,
        key: "123456"
    }, function (err, license) {

        if (err) {
            res.send(err);
            console.log(err);
        }

        //Send user back to main page
        res.writeHead(301, {
            'Location': '/',
            'Content-Type': 'text/plain'
        });
        res.end();
    }
    )

});

这是一种简单快捷的方式来实现您所需要的,因为Gson开箱即用地解析了地图,但要小心:如果您有更多这样的属性,它可能会更好为那个

创建一个新类