JSON对象首字母大小写转换

本文介绍了一个Java工具类,用于将JSONObject和JSONArray中的键名按指定模式(小写首字母或全大写)进行转换。通过实例展示了如何使用transformJsonKey和transformJsonArray方法实现键名的规范化处理。
摘要由CSDN通过智能技术生成
package com.cyhl.cs.util;

import jdk.nashorn.internal.runtime.regexp.joni.encoding.CharacterType;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.util.Iterator;

/**
 * @author gaojh
 * @version 1.0.0
 * @ClassName Test.java
 * @Description TODO
 */
public class Test {


    private static String STRING_CLAZZ = "String";
    private static String JSONOBJECT_CLAZZ = "JSONObject";
    private static String JSONARRAY_CLAZZ = "JSONArray";

    public static String INITIAL_SCHEMA = "initial"; //首字母
    public static String ALL_SCHEMA = "all"; //所有

    /**
     * @throws
     * @title transformJsonKey
     * @description   JsonKey 转换工具
     * @author gaojh
     * @param: jsonObject
     * @param: transition   转换类型
     * @param: pattern   转换模式
     * @return: net.sf.json.JSONObject
     */
    public static JSONObject transformJsonKey(JSONObject jsonObject, Integer transition, String pattern) {
        //验空判断
        if (null == jsonObject || null == transition || StringUtils.isBlank(pattern)) {
            return null;
        }
        JSONObject jsonTemp = new JSONObject();
        Iterator iterator = jsonObject.keys();
        while (iterator.hasNext()) {
            String jsonKey = (String) iterator.next();
            Object valueObject = jsonObject.get(jsonKey);
            //转换key
            String sourceKey = transform(jsonKey, transition, pattern);

            if (valueObject.getClass().toString().endsWith(STRING_CLAZZ)) {
                jsonTemp.accumulate(sourceKey, valueObject);
            } else if (valueObject.getClass().toString().endsWith(JSONOBJECT_CLAZZ)) {//对象套对象
                JSONObject checkObject = JSONObject.fromObject(valueObject);
                if (!checkObject.isEmpty()) {//json对象进行递归调用 返回json对象
                    jsonTemp.accumulate(sourceKey, transformJsonKey((JSONObject) valueObject, transition, pattern));
                } else {//空对象直接 赋值
                    jsonTemp.accumulate(sourceKey, "{}");
                }
            } else if (valueObject.getClass().toString().endsWith(JSONARRAY_CLAZZ)) {//对象套数组
                jsonTemp.accumulate(sourceKey, transformJsonArray(jsonObject.getJSONArray(jsonKey), transition, pattern));
            }
        }
        return jsonTemp;
    }

    /**
     * @throws
     * @title transformJsonArray
     * @description   JsonKey 转换工具
     * @author gaojh
     * @param: jsonArray
     * @param: transition   转换类型
     * @param: pattern   转换模式
     * @return: net.sf.json.JSONArray
     */
    public static JSONArray transformJsonArray(JSONArray jsonArray, Integer transition, String pattern) {
        JSONArray arrayTemp = new JSONArray();
        if (null != jsonArray && jsonArray.size() > 0) {
            for (Object object : jsonArray) {
                if (object.getClass().toString().endsWith(JSONOBJECT_CLAZZ)) {
                    arrayTemp.add(transformJsonKey((JSONObject) object, transition, pattern));
                } else if (object.getClass().toString().endsWith(JSONARRAY_CLAZZ)) {
                    arrayTemp.add(transformJsonArray((JSONArray) object, transition, pattern));
                }
            }
        }
        return arrayTemp;
    }

    private static String transform(String jsonKey, Integer transition, String pattern) {
        String sourceKey = "";
        if (CharacterType.LOWER == transition) { //小写
            if (INITIAL_SCHEMA.equals(pattern)) {
                String start = jsonKey.substring(0, 1).toLowerCase();
                String end = jsonKey.substring(1);
                sourceKey = start + end;
            } else if (ALL_SCHEMA.equals(pattern)) {
                sourceKey = jsonKey.toLowerCase();
            } else {
                System.out.printf("ERROR - 无效转换类型");
                throw new RuntimeException();
            }
        } else if (CharacterType.UPPER == transition) {//大写
            if (INITIAL_SCHEMA.equals(pattern)) {
                String start = jsonKey.substring(0, 1).toUpperCase();
                String end = jsonKey.substring(1);
                sourceKey = start + end;
            } else if (ALL_SCHEMA.equals(pattern)) {
                sourceKey = jsonKey.toUpperCase();
            } else {
                System.out.printf("ERROR - 无效转换类型");
                throw new RuntimeException();
            }
        } else {
            System.out.printf("ERROR - 无效转换模式");
            throw new RuntimeException();
        }
        return sourceKey;
    }

    public static void main(String[] args) throws Exception {

        JSONObject j1 = new JSONObject();
        j1.put("UserName", "1");
        j1.put("PAssWord", "2");
        j1.put("ifNull", "3");

        JSONObject j2 = new JSONObject();
        j2.put("UserName", "1");
        j2.put("PAssWord", "2");
        j2.put("ifNull", "3");

        JSONObject j3 = new JSONObject();
        j3.put("UserName", "1");
        j3.put("PAssWord", "2");
        j3.put("ifNull", "3");
        JSONArray a1 = new JSONArray();

        a1.add(new JSONObject());
        a1.add(j3);
        a1.add(new JSONObject());

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("UserName", "1");
        jsonObject.put("PAssWord", "2");
        jsonObject.put("ifNull", "3");
        jsonObject.put("j0", new JSONObject());
        jsonObject.put("J1", j1);
        jsonObject.put("j2", j2);
        jsonObject.put("A1", a1);


        System.out.println("数据源            " + jsonObject.toString());

        //转小写  首字母模式
        JSONObject jsonObject1 = transformJsonKey(jsonObject, CharacterType.LOWER, Test.INITIAL_SCHEMA);
        System.out.println("转小写  首字母模式 " + jsonObject1.toString());

        //转大写  全字母模式
        JSONObject jsonObject2 = transformJsonKey(jsonObject, CharacterType.UPPER, Test.ALL_SCHEMA);
        System.out.println("转大写  全字母模式 " + jsonObject2.toString());

    }
}

 人工手写,亲测可用。(注:嵌套数组可能出现问题请自行修改)

Java 的命名规范中,变量名和属性名应该采用驼峰命名法,即首字母小写,后面的单词首字母大写。而 JSON 中的属性名一般采用小写字母加下划线的形式,即 snake_case。 在 Java 中使用 Gson 库将实体类转换成 JSON 对象时,默认情况下会将属性名转换成 snake_case 格式。如果需要强制保留属性名的大小写形式,可以通过设置 Gson 的命名策略来实现。 以下是一个示例代码: ```java import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class MyClass { private String myProperty; public MyClass(String myProperty) { this.myProperty = myProperty; } public String getMyProperty() { return myProperty; } public void setMyProperty(String myProperty) { this.myProperty = myProperty; } public static void main(String[] args) { MyClass myObject = new MyClass("Hello, world!"); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY) // 强制保留属性名大小写 .create(); String json = gson.toJson(myObject); System.out.println(json); // 输出: {"myProperty":"Hello, world!"} } } ``` 在这个示例中,我们使用了 GsonBuilder 来创建 Gson 对象,并通过 setFieldNamingPolicy 方法将命名策略设置为 FieldNamingPolicy.IDENTITY,即强制保留属性名的大小写形式。然后将实体类对象转换成 JSON 字符串,并输出到控制台。 需要注意的是,如果属性名中包含下划线,Gson 会自动将下划线后面的字母转换成大写。例如,如果属性名为 "my_property",转换后的 JSON 属性名会变成 "myProperty"。如果需要保留下划线后面的字母的大小写形式,可以使用 FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES 命名策略,它会将下划线后面的字母保留原来的大小写形式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值