首页 > 代码库 > JSON序列化为java对象

JSON序列化为java对象

一. 前台(JS  面向对象)

1. 定义SearchView对象

function SearchView() {
}
SearchView.prototype.setViewName = function (viewName) {
    this.viewName = viewName;
}
SearchView.prototype.setViewType = function(viewType) {
    this.viewType = viewType;
}
SearchView.prototype.conditionList = new Array();//******conditionlist是一个对象数组,注意它的用法
 
SearchView.prototype.setCriteria = function (criteria) {
    this.criteria = criteria;//******creteria 也是对象,具体更searchview对象定义类似,注意它的用法
}
 
SearchView.prototype.setTenant = function(tenant) {
    this.tenant = tenant;
}

2. 把值设进SearchView对象中

var searchView = new SearchView();
    searchView.setViewName(viewName);
    searchView.setViewType(viewType);
    searchView.setCriteria(criteria);
    searchView.setTenant(tenant);
    searchView.conditionList = conditionList;

3. 关于conditionList对象数组定义并设进SearchView对象中:

var conditionList = new Array();
   $.each(conditionList, function (index, condition) {
        condition.fieldName = fieldName ;
        condition.operatorTxt = operatorTxt ;
        condition.fieldInfoTxt = fieldInfoTxt ;
        condition.conditionValue =$.trim(condition.conditionValue);
    });
    searchView.conditionList = conditionList;

4. ajax 提交表单到后台,注意红色部分,这是需要JSON序列化string之后提交到后台然后解析为java bean

 $.ajax({
        url:home + ‘UserSearchViewAction.do?operation=update‘,
        type:‘POST‘,
        dataType:‘json‘,
        data:{
            ‘searchView‘:JSON.stringify(searchView)//*********注意,需要序列化对象后提交到后台
        },
        success:function (data) {
           
        }
    });

二、后台

1.定义相应的bean对象

searchView.java

String viewName;
    String viewType;
    List<Condition> conditionList;
    String tenant;
    Criteria criteria;

Condition.java

private String conditionValue;
    private String fieldName;// field name
    private String operatorTxt; //operator value
    private String fieldInfoTxt;//field value

Criteria.java

 int viewId;
    String logicType;
    String advanceFilter;
    int criteriaType;

2.处理传过来的json对象并转换为javabean

 // parse jsonString to SearchView Object
        String searchViewJSON = request.getParameter("searchView");
         
        ObjectMapper objectMapper = new ObjectMapper();
        SearchView searchView = objectMapper.readValue(searchViewJSON, SearchView.class);

OK  到目前位置,json转换为javabean的例子就做完了,最后展示下json对象实例

{
    "viewName""t1"
    "viewType""Dynamic"
    "criteria": {
        "logicType""AND"
        "advanceFilter""1"
    }, 
    "tenant""DarlenSC"
    "conditionList": [
        {
            "fieldName""Active"
            "operatorTxt""Is not empty"
            "fieldInfoTxt"""
            "fieldId""8"
            "conditionValue"""
            "operation""ISNOTNULL"
            "conditionOrder"1
        }
    ]
}