
import javaioStringWriter;
import javautilHashMap;
import javautilList;
import javautilMap;
import orgcodehausjacksonJsonFactory;
import orgcodehausjacksonJsonGenerator;
import orgcodehausjacksonJsonParserFeature;
import orgcodehausjacksonmapJsonSerializer;
import orgcodehausjacksonmapObjectMapper;
import orgcodehausjacksonmapSerializationConfigFeature;
import orgcodehausjacksontypeTypeReference;
public class JsonUtils
{
private static ObjectMapper mapper = null;
static { mapper = new ObjectMapper();
mapperconfigure(SerializationConfigFeatureFAIL_ON_EMPTY_BEANS, false);
mapperconfigure(JsonParserFeatureALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
}
public static String toJson(Object target)
{
String json = "";
try {
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory()createJsonGenerator(sw);
mapperwriteValue(gen, target);
genclose();
json = swtoString();
}
catch (Exception e) {
throw new UnexpectedException("对象转换Json字符串出错," + targettoString(), e);
}
return json;
}
}
一般都是后台直接拼接好JSON格式返回,页面解析。
给你看个例子:
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 401 Transitional//EN" ">
PHP获取JSON的数据可以使用内置的 json_decode() 就可以解码为PHP变量,可根据自己需要的格式来进行格式化并提交到数据库。
例如:
<php$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
>
将会输出
object(stdClass)#1 (5) {["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
遍历结果集的时候,每次都新new了一个map,所以每次都是往map里面装了一个数据,
需要把map放到外面去实例化,然后再while里面去添加结果集的每个数据:
while(rsnext()){
map=new HashMap();
mapput(rsgetString(1), rsgetString(2));
}
可以直接将对象转json字符串,看你使用的什么后台语言,像java的话,可以使用Goon ,fastjson这些第三方库很方便的转换,其它语言的话也是有相应的工具和方法的,希望采纳,谢谢!
参考资料:
1 不用框架
传统方式用jdbc读取数据库数据到resultset,
a 通过json工具:将resultset中数据写到list里,通过json工具(如fastjson)转换成json字符串,返回到前台
b 直接通过resultset吧数据拼写成json格式字符串写到前台
2 框架
如struts2+spring, jdbctemple支持将读取结果直接返回给list, 将result类型设置生json即可,前台可直接获取json数据
以上就是关于咨询一下数据库里通过SQL结构化查询出的表数据记录怎么转换为JSON格式全部的内容,包括:咨询一下数据库里通过SQL结构化查询出的表数据记录怎么转换为JSON格式、ajax获取数据,应该返回json用js拼接 还是在后台拼接HTML完再返回、php 怎样获取 返回的json值提交到数据库等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)