您的位置:首页 > Web前端 > JavaScript

json 使用中代码复制

2012-08-23 15:23 169 查看
js中

数组的使用
var array = new Array();
var obj = {};
obj.number=number;
array.push(obj);

if(r){
var parameter = getFormParm("#bodyDiv :input");
parameter.array = array;
var jsonStr=JSON.stringify(parameter);
$.ajax({
type : "post",
dataType : "json",
data : {
jsonStr : jsonStr
},
url : "recipe.do?method=save",
success : function(data) {
$.messager.alert("提示", "操作成功");
$("#companyNo").val('');
$("#nhc01_editInfoDiv :input,textarea").val('');
$("#seridNumber").val(data.serid);
$("#versions").val(data.versions);
$("#receptumDiv").html('<fieldset><table id="drugInfo" style="width: 900px;font-size: 12px;" border="0" align="center"><tr align="center"><th>药名</th><th>数量</th><th>单价</th><th>小计</th><th>用法</th><th>操作</th></tr></table></fieldset>');
}
});
}


action中

public @ResponseBody
SeridNumber recipeSave(HttpServletRequest request, String jsonStr){
JSONObject jsonObj = new JSONObject(jsonStr);
Recipe recipe = new Recipe();
recipe.setId(jsonObj.optString("id"));
setValueFromJson(jsonObj, recipe);// JSON类型转换成 对象
JSONArray jsonArray = jsonObj.optJSONArray("array"); // 获得前面传过来的array 变量

/**
* 保存单据下面的药品
* */
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.optJSONObject(i);
if (obj.length() == 0) {
continue;
}
String drugName = obj.optString("drugName");
String numbers = obj.optString("number");
String unitPrice = obj.optString("unitPrice");
String subtotal = obj.optString("subtotal");
String usage = obj.optString("usage");
RecipeMedical recipeMedical = new RecipeMedical(recipeId,
drugName, numbers, unitPrice, subtotal, usage);
recipeMedical.setDelFlag("0");

recipeMedicalBO.saveRecipeMedical(recipeMedical);
}
}

//将JSON转换成对像
private Object setValueFromJson(JSONObject jsonObj, Object object)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, ParseException {
if (jsonObj == null || object == null || jsonObj.length() == 0) {
return null;
}
Method[] methods = object.getClass().getMethods();
for (Method m : methods) {
String mName = m.getName();

if (!mName.startsWith("set")) {
continue;
}
String firstLetter = mName.substring(3, 4);
String otherLetter = mName.substring(4);

String name = firstLetter.toLowerCase() + otherLetter;
String value = jsonObj.optString(name);
// 从JSON中解析出数据
if (value.trim().equals("")) {
continue;
}

Class[] parasClass = m.getParameterTypes();

if (parasClass.length != 1) {
continue;
}
// 判断方法参数类型
String paraType = parasClass[0].getName();
if (paraType.equals("java.lang.String")) {
m.invoke(object, value);
} else if (paraType.equals("java.lang.Integer")) {
m.invoke(object, Integer.parseInt(value));
} else if (paraType.equals("java.math.Bigdecimal")) {
m.invoke(object, new BigDecimal(value));
}
}
return object;
}


主要用了类型转换用的

宝贝网址:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: