组装json格式报文 -- java内部类

新手参考

/**
*   举例net.sf.json.JSONObject.fromObject(obj)生成json报文方式
*  创建请求报文对应demo类 
*/
public class UnderwritingCustomer extends CustomerBaseInfo{
    // 客户联系方式节点
    private PartyContactTrans partyContact;
    public PartyContactTrans getPartyContact() {
            return partyContact;
    }
    public void setPartyContact(PartyContactTrans partyContact) {
        this.partyContact = partyContact;
    }
    /**
     * (内部类)请求报文 - 客户联系方式节点
     * @author caisq
     */
    public static class PartyContactTrans {
        // 邮箱
        private String email;
        // 手机号码
        private String mobile;
        //省略其他节点字段...
        //构造方法 - 方便初始化
        public PartyContactTrans(){}
        public PartyContactTrans(String email,String mobile){
            this.email = email;
            this.mobile = mobile;
        }
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
        public String getMobile() {
            return mobile;
        }
        public void setMobile(String mobile) {
            this.mobile = mobile;
        }
    }
}
//报文组装
public static String marshallerJsonBody(){
    //创建对象set对应属性值
    UnderwritingCustomer customer = new UnderwritingCustomer();
    PartyContactTrans partyContact = new PartyContactTrans();
    partyContact.setEmail("[email protected]");
    partyContact.setMobile("186163****1");
    customer.setPartyContact(partyContact);
    //objToJson
    if(customer!= null){
        return JSONObject.fromObject(obj).toString();
    }
    return "";
}

PS:
1. java内部类详解链接 >>>
2. 例子比较简单,可按示例多重拓展
2. 使用静态内部类,不然实例化时候会报错。
3. 对于特殊格式报文,可单独对内部类toJson,然后合成报文体。
报文模版示例:

"customers": [
    {
        "partyId": 1,
        "person": {
            "@typeName": "PersonInputFounder",
            "certiCode": "1231411232",
            "certiType": 1,
            "certiEndDate": "9999-12-31",
        }
    },
    {
        "partyId": 2,
        "partyContact": {
            "email": "974367409@qq.com",
            "mobile": "18616318161"
        },
        "bankAccounts": [
            {
                "@typeName": "BankAccountInput",
                "bankAccount": "124241212212",
                "partyId": 2,
                "bankCode": "011"
            }
        ]
    }
]

—————————————————————加长版分割线—————————————————————————–

import net.sf.json.JSONObject;

JSONObject bodyJson = new JSONObject();
JSONObject claimantJson = new JSONObject();
claimantJson.element("claimant", claimant);
String claimantStr = claimantJson.toString().substring(12,claimantJson.toString().length()-1);
JSONObject dangerJson = new JSONObject();
dangerJson.element("danger", danger);
String dangerJsonStr = dangerJson.toString().substring(10,dangerJson.toString().length()-1);
JSONObject customersJson = new JSONObject();
customersJson.element("", "["+dangerJsonStr+","+claimantStr+"]");
bodyJson.element("extensionObject", extensionObject);
bodyJson.element("customers", "["+dangerJsonStr+","+claimantStr+"]");
String body = bodyJson.toString().replace("typeName", "@typeName");

—- end & 留言私信 —-

附个工具类代码
`import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
* 描述:JSON转Object V2.0 支持List、Set、Object类型
*/
public class JSONUtils {

/**
 * 方法名称: jsonMappedObj
* 描述:JSON 自动映射成对对象Object : * 属性支持: * 基本类型、String、Set、List、Object 等 * @param json * @return */ @SuppressWarnings("rawtypes") public static Object jsonToObj(String className ,String json){ Object obj = null; try { obj = getObject(className); Class clzz = getInstance(className); JSONObject jsonObject = getJson(json); jsonToObj(className, jsonObject, obj, clzz); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj ; } /** * 方法名称: jsonMappedObj
* 描述:JSON 自动映射成对对象Object : * 属性支持: * 基本类型、String、Set、List、Object 等 * @param json * @return */ @SuppressWarnings("rawtypes") public static Object jsonMappedObj(Class clz ,String json){ Object obj = null ; try { String className = clz.getName(); obj = getObject(className); Class clzz = getInstance(className); JSONObject jsonObject = getJson(json); jsonToObj(className, jsonObject, obj, clzz); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj ; } /** * JSON --》 Object 属性只支持String类转换
* @param className 类 * @param json json数据 * @return
*/ @SuppressWarnings("rawtypes") public static Object josnListObj(Class clz ,String json){ Object obj = null ; try { String className = clz.getName(); obj = getObject(className); Class clzz = getInstance(className); JSONObject jsonObject = getJson(json); jsonToObj(className, jsonObject, obj, clzz); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null ; } public static String objToJosn(Object obj){ if(obj != null){ return JSONObject.fromObject(obj).toString(); } return "" ; } /** * Object - 》 XML 属性只支持String类转换
* @param obj 对象 * @return
*/ @SuppressWarnings("rawtypes") public static String froXML(Object obj){ SortedMap packageParams = new TreeMap(); Class clzz = obj.getClass(); for (Field f : clzz.getDeclaredFields()){ if(f.getGenericType().toString().equals("class java.lang.String")){ Method m = getMethod(clzz, "get" + getMethodName(f.getName())); String value = getValue(m, obj); if(value != null){ packageParams.put(f.getName(), value); } } } return objToXML(packageParams) ; } @SuppressWarnings("rawtypes") public static String getSign(Object obj){ SortedMap packageParams = new TreeMap(); Class clzz = obj.getClass(); for (Field f : clzz.getDeclaredFields()){ if(f.getGenericType().toString().equals("class java.lang.String")){ Method m = getMethod(clzz, "get" + getMethodName(f.getName())); String value = getValue(m, obj); if(value != null){ packageParams.put(f.getName(), value); } } } return objToXML(packageParams) ; } private static String getValue(Method method ,Object obj){ String value = null ; try { value = (String) method.invoke(obj); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } return value ; } @SuppressWarnings({ "unchecked", "rawtypes" }) private static Method getMethod(Class clzz ,String name){ Method method = null ; try { method = clzz.getMethod(name); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } return method ; } private static String getMethodName(String fildeName){ byte[] items = fildeName.getBytes(); items[0] = (byte) ((char) items[0] - 'a' + 'A'); return new String(items); } @SuppressWarnings("rawtypes") private static Field getField(Class clzz ,String labelName){ Field field = null ; try { field = clzz.getDeclaredField(labelName); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchFieldException e) { // TODO Auto-generated catch block e.printStackTrace(); } return field ; } private static JSONObject getJson(String json){ JSONObject jsonObject = null ; try { jsonObject = JSONObject.fromObject(json) ; } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return jsonObject ; } private static Object getObject(String className){ Object obj = null ; try { obj = Class.forName(className).newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return obj ; } private static void analysisAttribute(Class clzz, JSONObject jsonObject, Object obj, Class zl){ for(Field fd : getFields(zl)){ analysisValue(getIterator(jsonObject), jsonObject, fd, obj, clzz); } } private static void analysisValue(Iterator iterator, JSONObject json, Field field, Object obj, Class clzz){ while(iterator.hasNext()){ String key = getKey(iterator); Object value = getValue(key, json); if(checkAttribute(field, key) && checkIsEmpty(value)){ checkAttributeType(field, obj, clzz, key, value); } } }

// private static void analysisValues(Iterator iterator, JSONObject json, Field field, Object obj, Class clzz){
// while(iterator.hasNext()){
// String key = getJSONArray(iterator);
// Object value = getValue(key, json);
// if(checkAttribute(field, key)){
// checkAttributeType(field, obj, clzz, key, value);
// }
// }
// }

private static void checkAttributeType(Field field, Object obj, Class clzz, String key, Object value){
    if(checkAttribute(field, key)){
        if(checkListType(field)){ 
            setTypeValue(field, obj, clzz, key, setListType(field, obj, value));
        }else if(checkSetType(field)){ 
            setTypeValue(field, obj, clzz, key, setSetType(field, obj, value));
        }else if(checkObject(field)){
            setTypeValue(field, obj, clzz, key, setObjectType(field, value));
        }else{
            setTypeValue(field, obj, clzz, key, value);
        }
    }
}

private static List setListType(Field field, Object obj, Object value){
    List list = new ArrayList();
    Iterator it = getJSONArray(value.toString()).iterator(); 
    Class clz = getClassInstantiation(getParameterizedType(getType(field)));
    Field [] fs = getFields(clz);
    while(it.hasNext()){  
        Object oj = getObject(clz.getName()); 
        JSONObject jso =  (JSONObject) it.next();  
        for(Field fi : fs){ 
            Iterator ittor = jso.keys() ;
            analysisValue(ittor, jso, fi, oj, clz);
        } 
        list.add(oj); 
    } 
    return list ;
}

private static Set setSetType(Field field, Object obj, Object value){
    Set set = new HashSet();
    Class clz = getClassInstantiation(getParameterizedType(getType(field)));
    Iterator it = getJSONArray(value.toString()).iterator();
    Field [] fs = getFields(clz);
    while(it.hasNext()){  
        Object oj = getObject(clz.getName()); 
        JSONObject jso =  (JSONObject) it.next();  
        for(Field fi : fs){ 
            Iterator ittor = jso.keys() ;
            analysisValue(ittor, jso, fi, oj, clz);
        } 
        set.add(oj); 
    }  
    return set ;
}

private static  Object setObjectType(Field field, Object value){
    Class clzz = field.getType() ;
    Object oj = getObject(clzz.getName()); 
    analysisAttribute(clzz, getJson(value.toString()), oj, clzz);
    return oj ;
}

private static Object getValue(String key, JSONObject json){
    return json.get(key);
}

private static String getKey(Iterator iterator){
     return (String) iterator.next();  
}

private static JSONObject getKeyJson(Iterator iterator){
     return (JSONObject) iterator.next();  
}

private static Iterator getIterator(JSONObject jsonObject){
    return jsonObject.keys();
}

private static void jsonToObj(String className, JSONObject jsonObject, Object obj, Class clzz){
    analysisAttribute(clzz, jsonObject, obj, getInstance(className));
}

private static Field[] getFields(Class clzz){
    return clzz.getDeclaredFields();
}

private static Class getClassInstantiation(ParameterizedType paraType){
    return (Class)paraType.getActualTypeArguments()[0]; 
}

private static ParameterizedType getParameterizedType(Type type){
    return (ParameterizedType) type;
}

private static Type getType(Field field){
    return field.getGenericType();
}

private static JSONArray getJSONArray(String json){
    return JSONArray.fromObject(json);
}

public static void setAccessibleFlag(Field field){
    field.setAccessible(true);
}

private static void setTypeValue(Field field, Object obj, Class clzz, String key, Object value){
    if(checkAttribute(field, key)){
        try { 
            checkType(getDeclaredField(clzz, key), obj, value);
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

private static boolean checkAttribute(Field field, String attribute){
    boolean flag = false ;
    if(field.getName().toUpperCase().equals(attribute.toUpperCase())){
        flag = true ;
    }
    return flag ;
}

public static Field getDeclaredField(Class clz, String key){
    return getField(clz, key);

}

public static void checkType(Field field, Object obj, Object value) throws NumberFormatException, IllegalArgumentException, IllegalAccessException{
    setAccessibleFlag(field);
    if(checkInt(field)){ 
        field.setInt(obj, Integer.parseInt(value.toString()));
    }else if(checkFloat(field)){
        field.setFloat(obj, Float.parseFloat(value.toString()));
    }else if(checkDouble(field)){
        field.setDouble(obj, Double.parseDouble(value.toString()));
    }else if(checkShort(field)){
        field.setShort(obj, Short.parseShort(value.toString()));
    }else if(checkLong(field)){
        field.setLong(obj, Long.parseLong(value.toString()));
    }else if(checkByte(field)){
        field.setByte(obj, Byte.parseByte(value.toString()));
    }else if(checkBoolean(field)){
        field.setBoolean(obj, Boolean.parseBoolean(value.toString()));
    }else{
        field.set(obj, value);
    }
} 

public static boolean checkInt(Field field){
    boolean flag = false ;
    if(field.getType().equals(int.class)){
        flag = true ;
    } 
    return flag ;
}

public static boolean checkFloat(Field field){
    boolean flag = false ;
    if(field.getType().equals(float.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkDouble(Field field){
    boolean flag = false ;
    if(field.getType().equals(double.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkLong(Field field){
    boolean flag = false ;
    if(field.getType().equals(long.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkChar(Field field){
    boolean flag = false ;
    if(field.getType().equals(char.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkByte(Field field){
    boolean flag = false ;
    if(field.getType().equals(byte.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkShort(Field field){
    boolean flag = false ;
    if(field.getType().equals(short.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkBoolean(Field field){
    boolean flag = false ;
    if(field.getType().equals(boolean.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkListType(Field field){
    boolean flag = false ;
    if(field.getType().equals(java.util.List.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkSetType(Field field){
    boolean flag = false ;
    if(field.getType().equals(java.util.Set.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkDateType(Field field){
    boolean flag = false ;
    if(field.getType().equals(java.util.Date.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkStringType(Field field){
    boolean flag = false ;
    if(field.getType().equals(String.class)){
        flag = true ;
    }
    return flag ;
}

private static boolean checkIntegerType(Field field){
    boolean flag = false ;
    if(field.getType().equals(java.lang.Integer.class)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkType(Field field){
    boolean flag = false ;
    if(checkInt(field)){
        flag = true ;
    }else if(checkFloat(field)){
        flag = true ;
    }else if(checkDouble(field)){
        flag = true ;
    }else if(checkLong(field)){
        flag = true ;
    }else if(checkChar(field)){
        flag = true ;
    }else if(checkByte(field)){
        flag = true ;
    }else if(checkShort(field)){
        flag = true ;
    }else if(checkBoolean(field)){
        flag = true ;
    }else if(checkDateType(field)){
        flag = true ;
    }else if(checkStringType(field)){
        flag = true ;
    }else if(checkIntegerType(field)){
        flag = true ;
    }
    return flag ;
}

public static boolean checkObject(Field field){
    boolean flag = false ;
    if(!field.getType().toString().startsWith("java.") && !checkType(field)){
        flag = true ;
    }
    return flag ;
}

@SuppressWarnings("rawtypes")
private static void jsonListObj(String className, JSONObject jsonObject, Object obj, Class clzz){
    for (Field field : getInstance(className).getDeclaredFields()) { 
        Iterator iterator = jsonObject.keys() ;
        while(iterator.hasNext()){  
            String key = (String) iterator.next();  
            String value = jsonObject.getString(key);  
            if(field.getName().toUpperCase().equals(key.toUpperCase())){
                field = getField(clzz, key);
                field.setAccessible(true);
                try {
                    field.set(obj, value);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

@SuppressWarnings("rawtypes")
private static Class getInstance(String className){
    Class clzz = null ;
    try {
        clzz = Class.forName(className).newInstance().getClass();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return clzz ;
}

private static boolean checkIsEmpty(Object obj){
    boolean flag = false ; 
    if(obj != null && !"null".equals(obj.toString()) && !"[]".equals(obj.toString())){
        flag = true ;
    }
    return flag ;
}

 @SuppressWarnings("rawtypes")
private static String objToXML(SortedMap parameters) {
     StringBuilder sb2 = new StringBuilder();
    try {
        sb2.append(""+"\n"+"");
        sb2.append("\n");
        Set es = parameters.entrySet();  
        Iterator it = es.iterator();  
        while(it.hasNext()) {  
        Map.Entry entry = (Map.Entry)it.next();  
        String k = (String)entry.getKey();  
        Object v = entry.getValue(); 
        sb2.append("<" + initialUpper(k) + ">");
        if("messageType".equals(k)){
            sb2.append(v.equals("text") ? "1" : "2");
        }else{
            sb2.append(v);
        }
        sb2.append("");
        sb2.append("\n");
    }  
        sb2.append("");

    } catch (Exception e) {
        e.printStackTrace();
    }
    return sb2.toString() ;
}

 /**
 * GBK转UTF-8
* @param gbk * @return
*/ public static String gbkToUtf8(String gbk){ String utf8 = null ; try { utf8 = new String(new String(gbk.getBytes("UTF-8"),"ISO-8859-1").getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return utf8 ; } public static String initialUpper(String convertString){ return convertString.substring(0, 1).toUpperCase()+convertString.substring(1, convertString.length()); } public static String initialLower(String convertString){ return convertString.substring(0, 1).toLowerCase()+convertString.substring(1, convertString.length()); }

}
`

你可能感兴趣的:(java,json报文)