gson Java:JSON反序列化将lower_case转换为camelCase

e4eetjau  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(162)

我正在尝试将我的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类的基础上,在stackoverflow之前的帖子。

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;
    }

当我使用上面的deserilizer时,虽然它能够将一些json数组对象的键转换为camle大小写......但我可以看到它只对每个数组中的一个jsonobject进行了转换,而没有将其他数组对象转换为consideration.as,如下所示。

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"
       }
    }

我知道stackoverflow中有很多可用的帖子,我在这个程度上完全是基于这些帖子,但由于我是Java和json serilization的新手,我无法再进步了...在这方面的任何帮助都非常感谢提前感谢

5jvtdoz2

5jvtdoz21#

您可以使用以下代码获取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"
  } ]
}

相关问题