有什么办法可以创建带有大写键的JSON对象? [英] Is there any way to create JSON object with keys as upper case?

查看:100
本文介绍了有什么办法可以创建带有大写键的JSON对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

项目:使用REST网络服务的Android应用
使用:
客户-排球
服务器API-泽西岛
转换器:Gson

Project: Android app using REST web service
Using:
Client - Volley
Server API - Jersey
Converter: Gson

这是我第一次在这里提出问题,我将提供逃避"此代码约定的方式.由于我正在一个已经将POJO字段定义为大写的项目(不幸的是,我无法更改它),因此我不得不找到一种方法来修复JSON字符串并将其转换为大写POJO的实例.

This is my first time asking a question here, and i will provide my way of "evading" this code convention. Since i am working on a project where POJO fields are already defined as upper-case (sadly, i cant change that), i had to find a way to fix JSON string and convert it to an instance of uppercase POJO.

所以基本上是这样的:客户端POJO<-> JSON对象与gson的相互转换<->服务器POJO

So basicaly its: client POJO <--> json object converted to/from gson <--> server POJO

所以,可以说我在Users.class

String USERNAME;

Jersey通过@Produces发送实例时,它遵循创建JSON的约定并发送对象

When Jersey sends an instance of via @Produces, it follows the convention of creating JSON and sends an object

{"username": "random_name"}

当通过gson.fromJSON从JSON转换时,客户端的POJO实例将为该字段获取空值(显然是因为JSONObject中的字段为小写字母).

When it gets converted from JSON via gson.fromJSON, an instance of a client's POJO will get null value for that field (obviously because field is in lower-case in JSONObject).

这是我使用解析JSONObject并将每个键都设置为大写的方法来管理它的方法:

This is how i managed it by using a method that parses JSONObject and puts each key as upper-case:

public static String fixJSONObject(JSONObject obj) {
    String jsonString = obj.toString();
    for(int i = 0; i<obj.names().length(); i++){
        try{
      obj.names().getString(i).toUpperCase());
           jsonString=jsonString.replace(obj.names().getString(i),
           obj.names().getString(i).toUpperCase());

        } catch(JSONException e) {
            e.printStackTrace();
        }
    }
    return jsonString;
}

幸运的是,由于gson.fromJSON()除了Class之外还需要String(不是JSONObject)作为参数,因此我设法解决了这一问题.

And luckily since gson.fromJSON() requires String (not a JSONObject) as a parameter besides Class, i managed to solve the problem this way.

所以,我的问题是:是否有任何优雅的方法使JSON忽略该代码约定并创建一个具有精确字段的JSON对象?在这种情况下:

So, my question would be: Is there any elegant way of making JSON ignore that code convention and create a JSON object with an exact field? In this case:

 {"USERNAME": "random_name"}

推荐答案

Jersey在内部使用JAXB来将bean编组为xml/json.因此,您始终可以使用@XmlElement批注并使用name属性来设置用于编组的属性名称

Jersey uses JAXB internally to marshall beans to xml/json. So you can always use @XmlElement annotation and use name attribute to set the attribute name to be used for marshalling

@XmlElement(name="USERNAME")
String USERNAME;

这篇关于有什么办法可以创建带有大写键的JSON对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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