如何在Java代码中动态生成和检索JSON? [英] How to Dynamically generate and retrieve JSON in Java code?

查看:273
本文介绍了如何在Java代码中动态生成和检索JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我们必须将不同的JSON发送到不同的服务器.

I have a use case where we have to send different JSONs to different servers.

区别仅在于JSON密钥之间,密钥携带的含义相同,数据也相同.

The difference is only between JSON keys, the meaning the keys carry is same and so is the data.

例如,服务器XYZ希望以以下格式发送JSON数据:

For example server XYZ wants JSON data to be sent in this format:

{ "firstName":"Sam", "lastName":"Jones"}

现在服务器ABC希望以以下格式发送JSON数据:

Now server ABC wants JSON data to be sent in this format:

{ "fName":"Sam", "lName":"Jones"}

然后通过POJO填充firstName和lastName数据.

And firstName and lastName data is populated via a POJO.

那么,我该如何实现呢?我不想在if-else条件下弄乱代码.

So, How do I achieve this? I do not want to clutter the code with if-else conditions.

但是wnat可以像动态加载模板一样工作,并创建JSON数据,然后将其检索回POJO.

But wnat to have something which would work like a template loaded dynamically and create the JSON data and also retrieve it back to the POJO.

推荐答案

该策略如何?

interface People{
    public String getRegularFirstName();
    public String getRegularLastName();
}

2.使用实现的接口定义每个POJO

//"{名字":"Sam","lastName":琼斯"}"

2. Define each POJO with implemented interface

//class for "{ "firstName":"Sam", "lastName":"Jones"}"

class PeopleData2 implements People{
    private String firstName;
    private String lastName;

    public String getRegularFirstName(){
        return firstName;
    }
    public String getRegularLastName(){
        return lastName;
    }
    //getter setter here..
}

//"{"的类:"sName":"Sam","lName":"Jones"}"

//class for "{ "fName":"Sam", "lName":"Jones"}"

class PeopleData1 implements People{
    private String fName;
    private String lName;

    public String getRegularFirstName(){
        return fName;
    }
    public String getRegularLastName(){
        return lName;
    }
    //getter setter here..
}

3.使每种json格式都应具有每个POJO类.

这不是严格意义上的策略,因为它需要添加类才能出现新格式. 但这将有助于系统扩展性

3. Make each json format deserved each POJO classes..

It is not dinamically strategy because it need to add class whe new format comes up. but it will help system scalability

这篇关于如何在Java代码中动态生成和检索JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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