解决JSONObject首字母默认变成小写问题

需要jar包
gson-2.2.4-javadoc.jar
gson-2.2.4-sources.jar
gson-2.2.4.jar

代码如下

import java.util.Iterator;

import org.json.JSONObject;

public class ObjectJsonZM {

    public static void main(String[] args) {
        String abc = "{" + "\"UserAttrs\"" + ":[{" + "\"To_Account\"" + ":"
                + "\"test\"" + "," + "\"Attrs\"" + ":{" + "\"sex\"" + ":"
                + "\"fale\"" + "}" + "}]}";
        System.out.println(abc);
        System.out.println(formatJson(abc).toString());
    }

    public static JSONObject formatJson(String orgJson) {
        JSONObject jo = new JSONObject();
        try {
            JSONObject jsonObject = new JSONObject(orgJson);
            Iterator iterator = jsonObject.keys();

            while (iterator.hasNext()) {
                String key = (String) iterator.next();
                char chars[] = key.toCharArray();
                if (key.length() > 1 && Character.isLowerCase(key.charAt(0))) {
                    chars[0] = Character.toUpperCase(chars[0]);
                }

                Boolean bl = jsonObject.isNull(key);
                if (bl) {
                    jo.put(new String(chars), bl);
                } else {
                    Object object = jsonObject.get(key);
                    try {
                        if (object instanceof Number) {
                            // Log.i("MainActivity-----------------",
                            // "result:1");
                            jo.put(new String(chars),
                                    ((Number) object).intValue());
                        } else {
                            // Log.i("MainActivity-----------------",
                            // "result:2");
                            jo.put(new String(chars), jsonObject.getString(key));
                        }
                    } catch (Exception e) {
                        jo.put(new String(chars), jsonObject.getString(key));
                    }
                }
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return jo;
    }

}

你可能感兴趣的:(javaee)