场景:json配置报文转换
遇到的问题:1.json报文转换成map,多节点如何处理?数组如何处理?
2.velocity模板处理数组
3.应用之间rabbitmq通讯map反序列化,数组报错?
知识点:
HashMap map中重要的两个方法map.containsKey()和map.contaisValue()
#foreach($key in [0..10])
$key
#end
#if($id == "")
#end
计数器 velocityCount
haspmap的属性可以在模板中使用
样例报文
{ "service":{ "service_header":{ "name":"张三", "age":"12" } "service_body":{ "info":[ { "address":"上海", "tel":"111" }, { "address":"北京", "tel":"020" } ] } } }
模板配置
{ "service":{ "service_header":{ "lastname":"${name}", "age":"${age}" } "service_body":{ "info":[ #set($infos={"address":"address","telphone":"tel"}) #foreach($key in ${infos}) { #foreach($key2 in $key.keySet()) #foreach($key3 in $infos.keySet()) #if($key2 == $infos.get($key3)) "$key3":"$key.get($key2)" #if($velocityCount != $key.size()) , #end #end #end #end } #if($velocityCount != $infos.size()) , #end #end ] } } }
测试代码
package com.sunline.nfs.process; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.StringWriter; import java.util.LinkedHashMap; import java.util.Map; import java.util.Properties; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import org.apache.velocity.app.VelocityEngine; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class velocityEngine { static Map<String,Object> jsonMap = new LinkedHashMap<String,Object>(); public static Map recursinMap(Map<String,Object> map){ net.sf.json.JSONObject jObject = new net.sf.json.JSONObject(); for(String key:map.keySet()){ String str = map.get(key).toString(); if(str.startsWith("{")){ /*com.alibaba.fastjson.JSONObject jObject = JSON.parseObject(str);*/ Map<String,Object> map2 = jObject.fromObject(str); if(!map.toString().endsWith(map2.toString()+"}")){ int i = map.toString().indexOf(map2.toString())+1; String value ="{" + map.toString().substring((i+map2.toString().length()),map.toString().length()); map2.put(key, value); } return recursinMap(map2); } else{ if(str.startsWith("[")){ JSONArray tmpMaps = JSONArray.fromObject(str); System.out.println("key="+key+" tmpMaps"+tmpMaps); jsonMap.put(key, tmpMaps); /*for(int i=0;i<tmpMaps.size();i++){ JSONObject job = tmpMaps.getJSONObject(i); Map<String,Object> jobMap = JSONObject.fromObject(job.toString()); for(String key2:jobMap.keySet()) jsonMap.put(key+i+key2, jobMap.get(key2)); } */ } else{ jsonMap.put(key, str); } } } return jsonMap; } @SuppressWarnings("null") public static void main(String[] args) throws IOException{ String filename = "ObtainAppNo.txt"; String json = readJson(filename); net.sf.json.JSONObject jObject = new net.sf.json.JSONObject(); Map<String,Object> map2 = jObject.fromObject(json); Map<String,Object> jsonMap = recursinMap(map2); System.out.println("-----" +jsonMap); //初始化参数 Properties properties=new Properties(); //设置velocity资源加载方式为class properties.setProperty("resource.loader", "class"); //设置velocity资源加载方式为file时的处理类 properties.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); //实例化一个VelocityEngine对象 VelocityEngine velocityEngine=new VelocityEngine(properties); //实例化一个VelocityContext VelocityContext context=new VelocityContext(); for(Object key :jsonMap.keySet()){ context.put((String)key, jsonMap.get(key)); } //实例化一个StringWriter StringWriter writer=new StringWriter(); //假若在com.velocity.test包下有一个hello.vm文件,那么加载路径为com/velocity/test/hello.vm // String json2 = readJson("2.txt"); // velocityEngine.mergeTemplate(json2, "gbk", context, writer); //这种方式是正确的 velocityEngine.mergeTemplate("2.txt", "gbk", context, writer); String str = writer.toString(); str = str.replaceAll("\\s*", ""); System.out.println("-----" +str); } public static String readJson(String filename){ Resource resource =new ClassPathResource(filename); File file; try { file = resource.getFile(); BufferedReader reader= new BufferedReader(new FileReader(file)); String temp=null; String str=""; while((temp=reader.readLine())!=null){ str = str + temp; } str=str.replace(" ", ""); return str; } catch (IOException e) { e.printStackTrace(); } return null; } }