Java:JSON反序列化将小写转换为camelCase

Posted

技术标签:

【中文标题】Java:JSON反序列化将小写转换为camelCase【英文标题】:Java : JSON Deserilization to convert the lower_case to camelCase 【发布时间】:2021-11-04 00:53:28 【问题描述】:

我正在尝试将我的 json 字符串中的键转换为 camelCase..我已经浏览了 *** 中的各种帖子,但无法找到解决方案..

我有一个以下格式的 json 字符串..

 
       "tech":[
          
             "id":"1",
             "company_name":"Microsoft",
             "country_of_origin":"USA"
          ,
          
             "id":"2",
             "company_name":"SAP",
             "country_of_origin":"Germany"
          
       ],
       "Manufacturing":[
          
             "id":"3",
             "company_name":"GM",
             "country_of_origin":"USA"
          ,
          
             "id":"4",
             "company_name":"BMW",
             "country_of_origin":"Germany"
          
       ]
    

预期响应

 
       "tech":[
          
             "id":"1",
             "companyName":"Microsoft",
              "countryOfOrigin":"USA"
          ,
          
             "id":"2",
             "companyName":"SAP",
             "countryOfOrigin":"Germany"
          
       ],
       "Manufacturing":[
          
             "id":"3",
             "companyName":"GM",
             "countryOfOrigin":"USA"
          ,
          
             "id":"4",
             "companyName":"BMW",
             "countryOfOrigin":"Germany"
          
       ]
    

我已经根据 *** 中的上一篇文章编写了一个 jsonDeserializer 类..

 Gson gson = new GsonBuilder()
                    .registerTypeAdapter(UpperCaseAdapter.TYPE, new UpperCaseAdapter())
                    .create();

            Map<String, List<Company>> mapDeserialized = gson.fromJson(jsonString, UpperCaseAdapter.TYPE);
            System.out.println(mapDeserialized);

还有脱硫剂

 public class UpperCaseAdapter implements JsonDeserializer<Map<String, Object>> 
        public static final Type TYPE = new TypeToken<Map<String, Object>>() .getType();
     
         @Override
        public Map<String, Object> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException 
            Map<String, Object> map = new HashMap<>();
            for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) 
                Object value = null;
                if (entry.getValue().isJsonPrimitive()) 
                    value = entry.getValue().getAsString();
                 else if (entry.getValue().isJsonObject()) 
                    value = context.deserialize(entry.getValue(), TYPE);
                 else if (entry.getValue().isJsonArray()) 
                    for(JsonElement jsonElement:entry.getValue().getAsJsonArray())
                        value=context.deserialize(jsonElement,TYPE);
                    
                 else if (entry.getValue().isJsonNull()) 
                     continue;
                
                map.put(CaseFormat.LOWER_UNDERSCORE.to(
                        CaseFormat.LOWER_CAMEL, entry.getKey()), value);
            
            return map;
        
    

模型类

  public class Company 
        private String id;
        private String compnayName;
        private String countryOfOrigin;
    

当我使用上述解串器时,虽然它能够将某些 json 数组对象的键转换为 camle 大小写....我可以看到它只对每个数组中的一个 jsonobject 执行此操作,而不采用其他数组对象在考虑中。如下图。

 Wrong Response i am getting with above serializer(missing other jsonobjecsts and the key manufacturing is converted to lower):        
     

       "tech="
          "companyName=SAP",
          id=2,
          "countryOfOrigin=Germany"
       ,
       "manufacturing="
          "companyName=BMW",
          id=4,
          "countryOfOrigin=Germany"
       
    
 

我知道 *** 中有很多可用的帖子,我只能基于这些帖子,但由于我是 Java 和 json 序列化的新手,我无法再进步......这方面的任何帮助都很大提前感谢感谢

【问题讨论】:

嗨,非常感谢您的帮助?? 【参考方案1】:

您可以使用以下代码获取CamelCase字符串;

static public class Company 
    private String id;
    private String companyName;
    private String countryOfOrigin;

    public Company() 
    

    public String getId() 
        return id;
    

    public void setId(String id) 
        this.id = id;
    

    public String getCompanyName() 
        return companyName;
    

    public void setCompanyName(String companyName) 
        this.companyName = companyName;
    

    public String getCountryOfOrigin() 
        return countryOfOrigin;
    

    public void setCountryOfOrigin(String countryOfOrigin) 
        this.countryOfOrigin = countryOfOrigin;
    


@Test
void t4() throws JsonProcessingException 



    ObjectMapper mapperSC = new ObjectMapper();
    mapperSC.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE);

    String data = " " +
            "   \"tech\":[ " +
            "       " +
            "         \"id\":\"1\", " +
            "            \"company_name\":\"Microsoft\", " +
            "            \"country_of_origin\":\"USA\" " +
            "      , " +
            "       " +
            "         \"id\":\"2\", " +
            "            \"company_name\":\"SAP\", " +
            "            \"country_of_origin\":\"Germany\" " +
            "       " +
            "      ], " +
            "      \"Manufacturing\":[ " +
            "       " +
            "         \"id\":\"3\", " +
            "            \"company_name\":\"GM\", " +
            "            \"country_of_origin\":\"USA\" " +
            "      , " +
            "       " +
            "         \"id\":\"4\", " +
            "            \"company_name\":\"BMW\", " +
            "            \"country_of_origin\":\"Germany\" " +
            "       " +
            "   ] " +
            "";


    TypeFactory tf = mapper.getTypeFactory();
    JavaType jt = tf.constructMapType(Map.class, tf.constructType(String.class), tf.constructArrayType(Company.class));
    Object o = mapperSC.readValue(data, jt);
    System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(o));


输出将是;


  "tech" : [ 
    "id" : "1",
    "companyName" : "Microsoft",
    "countryOfOrigin" : "USA"
  , 
    "id" : "2",
    "companyName" : "SAP",
    "countryOfOrigin" : "Germany"
   ],
  "Manufacturing" : [ 
    "id" : "3",
    "companyName" : "GM",
    "countryOfOrigin" : "USA"
  , 
    "id" : "4",
    "companyName" : "BMW",
    "countryOfOrigin" : "Germany"
   ]

【讨论】:

以上是关于Java:JSON反序列化将小写转换为camelCase的主要内容,如果未能解决你的问题,请参考以下文章

在将 json 反序列化为对象时,使用 jackson 将 asp.net / MS 专有 json Dateformat 转换为 java8 LocalDateTime

c# 多个json字符串反序列化

如何在 JSON 反序列化期间将引用转换为实例

使用Jackson将JSON数组反序列化为单个Java对象

vulhub漏洞复现Fastjson 1.2.24反序列化漏洞

将 Json 反序列化为实体框架无法将 int 转换为类型