NutzCN Logo
精华 @AdaptBy 适配 list 和 map 为 null
发布于 3146天前 作者 SniperZj 2860 次浏览 复制 上一个帖子 下一个帖子
标签:

@AdaptBy(type = JsonAdaptor.class)
@At("/test/cbom-imporHoursData")
public int imporHoursData(List hoursInsertData,Map<String, WorkHours> hoursUpdateData) {
hoursInsertData 与 hoursUpdateData 都为 null
}

jsp页面 ——————————————————————
<script type="text/javascript">

var ctx = '${base}';
var hoursInsertData = '${obj.hoursInsertData}';
var hoursUpdateData = '${obj.hoursUpdateData}';

$('#import').click(function(){
$.ajax({
"async" : false,
"type" : "POST",
"url" : ctx + '/test/test-imporHoursData.do',
"dataType" : "json",
"data": {hoursInsertData:hoursInsertData,hoursUpdateData:hoursUpdateData},
"success" : function(result){
if(result!=null){
clCloseMessage("成功导入"+result+"条成本工时单价数据!",false);
}
}
});
});

18 回复

要加@Param哦

都试过了 = =!!!

后台
map.put("hoursData", hoursData);
map.put("hoursInsertData", hoursInsertData);//list
map.put("hoursUpdateData", hoursUpdateData);//map
return map;

报错:org.nutz.json.JsonException: !Json syntax error nearby [row:1,col:1 char 'h'], reason: 'Unexpect String = hoursInsertData=%5BWorkHours(id%3Dnull%2C+productId%3D2077%2C+stageId%3D6%2C+quarterId%3D50%2C+workHours%3D0.0%2C+trColor%3D%23FFF%2C+kh%3D15646569%2C+quarterName%3D16q4%2C+stageName%3D%E5%A4%A7%E8%B4%A7%2C+errorMsg%3Dnull%2C+seq%3D1%2C+remark%3Dnull%2C+state%3D0%2C+creater%3D%E7%B3%BB%E7%BB%9F%E7%AE%A1%E7%90%86%E5%91%98%2C+createTime%3DMon+Apr+11+13%3A34%3A32+CST+2016%2C+updater%3Dnull%2C+updateTime%3Dnull%2C+cutTime%3D888.0%2C+cutPrice%3D21.0%2C+sewTime%3D31.0%2C+sewPrice%3D41.0%2C+packTime%3D51.0%2C+packPrice%3D61.0%2C+totalTime%3D71.0%2C+totalPrice%3D8.5155)%5D&hoursUpdateData=%7B%7D'
at org.nutz.json.impl.JsonTokenScan.readObject(JsonCompileImplV2.java:297)
at org.nutz.json.impl.JsonTokenScan.read(JsonCompileImplV2.java:354)
at org.nutz.json.impl.JsonCompileImplV2.parse(JsonCompileImplV2.java:26)
at org.nutz.json.Json.fromJson(Json.java:40)
at org.nutz.mvc.adaptor.JsonAdaptor.getReferObject(JsonAdaptor.java:41)
at org.nutz.mvc.adaptor.AbstractAdaptor.adapt(AbstractAdaptor.java:216)
at org.nutz.mvc.impl.processor.AdaptorProcessor.process(AdaptorProcessor.java:28)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.ActionFiltersProcessor.process(ActionFiltersProcessor.java:40)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.ModuleProcessor.process(ModuleProcessor.java:119)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.EncodingProcessor.process(EncodingProcessor.java:27)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.UpdateRequestAttributesProcessor.process(UpdateRequestAttributesProcessor.java:15)
at org.nutz.mvc.impl.NutActionChain.doChain(NutActionChain.java:44)
at org.nutz.mvc.impl.ActionInvoker.invoke(ActionInvoker.java:67)
at org.nutz.mvc.ActionHandler.handle(ActionHandler.java:31)
at org.nutz.mvc.NutFilter.doFilter(NutFilter.java:179)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at cn.calensoft.module.filters.Log4jInfoFilter.doFilter(Log4jInfoFilter.java:88)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)

var ctx = '${base}';
var hoursInsertData = '${obj.hoursInsertData}';
var hoursUpdateData = '${obj.hoursUpdateData}';
function clOpenMessage(message) {
$("#loading-div").dialog({
dialogClass : 'ui-dialog-grey',
height : 220,
width : 350,
modal : true,
closeOnEscape : false,
position: 'center',
});
if (null == message || message == "") {
message = "数据处理中...";
}
$("#loading-tip").html(message);
return false;
}

function clMessage(message) {
$("#loading-tip").html(message);
}

function clCloseMessage(message, flag) {
if (null == message || message == "") {
message = "数据处理完毕";
}
if (null == flag)
flag = true;
$("#loading-tip").html(message);

if (flag) {
    setTimeout(function() {
       $("#loading-div").dialog("close");
    }, 500);
}

}

$('#import').click(function(){
clOpenMessage("数据导入中,请稍后...");
$.ajax({
"async" : false,
"type" : "POST",
"url" : ctx + '/dev/cbom-imporHoursData.do',
"contentType": "application/json; charset=utf-8",
"dataType" : "json",
"data": {hoursInsertData:hoursInsertData,hoursUpdateData:hoursUpdateData},
"success" : function(result){
if(result!=null){
clCloseMessage("成功导入"+result+"条成本工时单价数据!",false);
}
}
});
});

@AdaptBy(type = JsonAdaptor.class)

那ajax的data必须是一个json字符串哦

"data": $.ToJSON({hoursInsertData:hoursInsertData,hoursUpdateData:hoursUpdateData}),

后台这样接收

@Param("hoursInsertData")List<xxxx> xxxx

$.ToJSON({hoursInsertData:hoursInsertData,hoursUpdateData:hoursUpdateData})
alert 出来是这种格式的 不是个json字符串 = =!!!
{"hoursInsertData":"[WorkHours(id=null, productId=2077, stageId=6, quarterId=50, workHours=0.0, trColor=#FFF, kh=15646569, quarterName=16q4, stageName=大货, errorMsg=null, seq=1, remark=null, state=0, creater=系统管理员, createTime=Mon Apr 11 15:49:48 CST 2016, updater=null, updateTime=null, cutTime=888.0, cutPrice=21.0, sewTime=31.0, sewPrice=41.0, packTime=51.0, packPrice=61.0, totalTime=71.0, totalPrice=8.5155)]","hoursUpdateData":"{}"}

org.nutz.castor.FailToCastObjectException: Fail to cast from <java.lang.String> to <java.util.List> for {[WorkHours(id=null, productId=2077, stageId=6, quarterId=50, workHours=0.0, trColor=#FFF, kh=15646569, quarterName=16q4, stageName=大货, errorMsg=null, seq=1, remark=null, state=0, creater=系统管理员, createTime=Mon Apr 11 15:49:48 CST 2016, updater=null, updateTime=null, cutTime=888.0, cutPrice=21.0, sewTime=31.0, sewPrice=41.0, packTime=51.0, packPrice=61.0, totalTime=71.0, totalPrice=8.5155)]} because:
JsonException:!Json syntax error nearby [row:1,col:19 char 'W'], reason: 'Unexpect String = WorkHours(id=null'
at org.nutz.castor.Castors.cast(Castors.java:264)
at org.nutz.castor.Castors.castTo(Castors.java:318)
at org.nutz.mvc.adaptor.injector.NameInjector.get(NameInjector.java:93)
at org.nutz.mvc.adaptor.AbstractAdaptor.adapt(AbstractAdaptor.java:247)
at org.nutz.mvc.impl.processor.AdaptorProcessor.process(AdaptorProcessor.java:28)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.ActionFiltersProcessor.process(ActionFiltersProcessor.java:40)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.ModuleProcessor.process(ModuleProcessor.java:119)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.EncodingProcessor.process(EncodingProcessor.java:27)
at org.nutz.mvc.impl.processor.AbstractProcessor.doNext(AbstractProcessor.java:44)
at org.nutz.mvc.impl.processor.UpdateRequestAttributesProcessor.process(UpdateRequestAttributesProcessor.java:15)
at org.nutz.mvc.impl.NutActionChain.doChain(NutActionChain.java:44)
at org.nutz.mvc.impl.ActionInvoker.invoke(ActionInvoker.java:67)
at org.nutz.mvc.ActionHandler.handle(ActionHandler.java:31)
at org.nutz.mvc.NutFilter.doFilter(NutFilter.java:179)

  1. 那是json字符串, 你是觉得"[WorkHours(id=null 这部分不是json? 那是因为你传给它的就是一个字符串, 不是对象(你把它拼成字符串了.)
  2. 解决第一点,按对象的方式转成json字符串, 代码就能通.

@At("/dev/cbom-imporHours")
@Ok("jsp:pages.dev.cbom.cbom-ImportHoursExcel")
public Object imporHours(String path) throws InvalidFormatException, FileNotFoundException, IOException, IllegalAccessException, InvocationTargetException {
return cbomService.imporHours(path);
}
map.put("hoursData", hoursData);
map.put("hoursInsertData", hoursInsertData);
map.put("hoursUpdateData", hoursUpdateData);
//后台直接 转json 字符串
map.put("hoursInsertDataJson", Json.toJson(hoursInsertData, JsonFormat.compact()));
map.put("hoursUpdateDataJson", Json.toJson(hoursUpdateData, JsonFormat.compact()));
return map;

var ctx = '${base}';
var hoursInsertData = '${obj.hoursInsertData}';
var hoursUpdateData = '${obj.hoursUpdateData}';
var hoursInsertDataJson = '${obj.hoursInsertDataJson}';
var hoursUpdateDataJson = '${obj.hoursUpdateDataJson}';
alert($.toJSON({hoursInsertData:hoursInsertDataJson,hoursUpdateData:hoursUpdateDataJson}));
{"hoursInsertData":"[{"productId":2077,"stageId":6,"quarterId":50,"workHours":0.0,"trColor":"#FFF","kh":"15646569","quarterName":"16q4","stageName":"大货","seq":"1","state":0,"creater":"系统管理员","createTime":"2016-04-11 19:47:54","cutTime":888.0,"cutPrice":21.0,"sewTime":31.0,"sewPrice":41.0,"packTime":51.0,"packPrice":61.0,"totalTime":71.0,"totalPrice":8.5155}]","hoursUpdateData":"{}"}

//后台适配到的对象
[{productId=2077, stageId=6, quarterId=50, workHours=0.0, trColor=#FFF, kh=15646569, quarterName=16q4, stageName=大货, seq=1, state=0, creater=系统管理员, createTime=2016-04-11 19:42:50, cutTime=888.0, cutPrice=21.0, sewTime=31.0, sewPrice=41.0, packTime=51.0, packPrice=61.0, totalTime=71.0, totalPrice=8.5155}]
执行 dao().insert(hoursInsertData); //异常
2016-04-11 19:53:32,214 - org.nutz.mvc.impl.processor.FailProcessor -688269 [http-bio-8080-exec-10] WARN - Error@/dev/cbom-imporHoursData :
java.lang.RuntimeException: Can not insert map without key '.table' :
{
productId :2077,
stageId :6,
quarterId :50,
workHours :0.0,
trColor :"#FFF",
kh :"15646569",
quarterName :"16q4",
stageName :"大货",
seq :"1",
state :0,
creater :"系统管理员",
createTime :"2016-04-11 19:42:50",
cutTime :888.0,
cutPrice :21.0,
sewTime :31.0,
sewPrice :41.0,
packTime :51.0,
packPrice :61.0,
totalTime :71.0,
totalPrice :8.5155
}
at org.nutz.lang.Lang.makeThrow(Lang.java:99)
at org.nutz.dao.impl.EntityHolder.getEntityBy(EntityHolder.java:181)
at org.nutz.dao.impl.NutDao._optBy(NutDao.java:921)
at org.nutz.dao.impl.NutDao.insert(NutDao.java:136)

insert一个map的话,需要.table属性哦,不然不知道应该插入到哪个表

哦,是泛型没识别到的样子?用的啥版本?

另外,贴代码的时候菜单里面的代码块啊,不然看得眼疼

晕 怎么会 类型是 map 呢 明明是 list 嘛 晕了
List hoursInsertData//
Map<String, WorkHours> hoursUpdateData// <key,WorkHours>
public int imporHoursData(List hoursInsertData,Map<String, WorkHours> hoursUpdateData) {
int count = 0;
if(hoursInsertData.size()>0){
dao().insert(hoursInsertData);
count += hoursInsertData.size();
}

    if(hoursUpdateData.size()>0){
       for (String key : hoursUpdateData.keySet()) {
         System.out.println(key.substring(0, key.indexOf("_")));
         dao().update(hoursUpdateData.get(key),key.substring(0, key.indexOf("_")));
       }
       count += hoursUpdateData.size();
    }
    return count;
}

public Entity<?> getEntityBy(Object obj)
/* / {
/
172 / Object first = Lang.first(obj);
/
/
/
174 / if (first == null) {
/
175 / return null;
/
/ }
/
/
/
178 / if ((first instanceof Map)) {
/
179 / Object tableName = ((Map)first).get(".table");
/
180 / if (null == tableName)
/
181 / throw Lang.makeThrow("Can not insert map without key '.table' : \n%s", new Object[] {
/
182 / Json.toJson(first, JsonFormat.forLook()) });
/
183 / return makeEntity(tableName.toString(), (Map)first);
/
/ }
/
/
/
186 / return getEntity(first.getClass());
/
*/ }

nutz-1.r.54.r2.jar = = !!!

用代码块重新发一次代码, 看得头晕

@At("/dev/cbom-imporHours")
	@Ok("jsp:pages.dev.cbom.cbom-ImportHoursExcel")
	public Object imporHours(String path) throws InvalidFormatException, FileNotFoundException, IOException, IllegalAccessException, InvocationTargetException {
		return cbomService.imporHours(path);
	}

	public Object imporHours(String path) throws InvalidFormatException, FileNotFoundException, IOException, IllegalAccessException, InvocationTargetException {
		....
		  map.put("hoursData", hoursData);
		  map.put("hoursInsertData", hoursInsertData);
		  map.put("hoursUpdateData", hoursUpdateData);
		  map.put("hoursInsertDataJson", Json.toJson(hoursInsertData, JsonFormat.compact()));
		  map.put("hoursUpdateDataJson", Json.toJson(hoursUpdateData, JsonFormat.compact()));
		return map;
	}



var ctx = '${base}';
var hoursInsertData = '${obj.hoursInsertData}';
var hoursUpdateData = '${obj.hoursUpdateData}';
var hoursInsertDataJson = '${obj.hoursInsertDataJson}';
var hoursUpdateDataJson = '${obj.hoursUpdateDataJson}';
...
$('#import').click(function(){
	//clOpenMessage("数据导入中,请稍后...");
	$.ajax({
		"async" : false,
	    "type" : "POST",
	    "url" : ctx + '/dev/cbom-imporHoursData.do',
	    "contentType": "application/json; charset=utf-8",
	    "dataType" : "json",
	    "data":$.toJSON({hoursInsertData:hoursInsertDataJson,hoursUpdateData:hoursUpdateDataJson}),
	    "success" : function(result){
	    	if(result!=null){
	    		clCloseMessage("成功导入"+result+"条成本工时单价数据!",false);
	    	}
	    }




	@AdaptBy(type = JsonAdaptor.class)
	@At("/dev/cbom-imporHoursData")
	public int imporHoursData(@Param("hoursInsertData") List<WorkHours> hoursInsertData,@Param("hoursUpdateData") Map<String, WorkHours> hoursUpdateData) {
		return cbomService.imporHoursData(hoursInsertData,hoursUpdateData);
	}
	});
});


	public int imporHoursData(List<WorkHours> hoursInsertData,Map<String, WorkHours> hoursUpdateData) {
		int count = 0;
		if(hoursInsertData.size()>0){
			dao().insert(hoursInsertData);
			count += hoursInsertData.size();
		}
		
		if(hoursUpdateData.size()>0){
			for (String key : hoursUpdateData.keySet()) {
				System.out.println(key.substring(0, key.indexOf("_")));
				dao().update(hoursUpdateData.get(key),key.substring(0, key.indexOf("_")));
			}
			count += hoursUpdateData.size();
		}
		return count;
	}

ok, 看来不行, 改成这样(手敲的,自行fix语法错误):

	public int imporHoursData(@Param("hoursInsertData") List<Map> _hoursInsertData, // 用map收
	                                         @Param("hoursUpdateData") Map<String, Map> _hoursUpdateData)  {
		List<HoursInsertData> hoursInsertData = new ArrayList<>();
		for (Map tmp : _hoursInsertData) {
		      hoursInsertData.add(Lang.map2Object(map, HoursInsertData.class))
		}
		// 同理,转换hoursUpdateData
       Map<String, WorkHours> hoursUpdateData = new HashMap();
	   for (Entry<String, Map> tmp : _hoursUpdateData.entrySet()) {
	       hoursUpdateData.put(tmp.getKey(), Lang.map2Object(map, WorkHours.class));
	   }
		return cbomService.imporHoursData(hoursInsertData,hoursUpdateData);
	}
	});

还有一个办法,就是需要多定义一个类

public class YourXXX {
    public List<WorkHours> hoursInsertData;
	public Map<String, WorkHours> hoursUpdateData;
}

入口方法就可以直接收了

public int imporHoursData(@Param("..")YourXXX master) {
    return cbomService.imporHoursData(master.hoursInsertData, master.hoursUpdateData);
} 

诶呀妈呀 终于 好了 thanks o(^▽^)o

添加回复
请先登陆
回到顶部