本文目录一览:
- 1、咨询一下数据库里通过SQL结构化查询出的表数据记录怎么转换为JSON格式?
- 2、json的赋值
- 3、Android 解析json问题
- 4、在eclipse中,如何导入json包和使用呢?
- 5、如何使用java创建json对象
- 6、Java解析json数据
咨询一下数据库里通过SQL结构化查询出的表数据记录怎么转换为JSON格式?
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParser.Feature;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig.Feature;
import org.codehaus.jackson.type.TypeReference;
public class JsonUtils
{
private static ObjectMapper mapper = null;
static { mapper = new ObjectMapper();
mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
}
public static String toJson(Object target)
{
String json = "";
try {
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
mapper.writeValue(gen, target);
gen.close();
json = sw.toString();
}
catch (Exception e) {
throw new UnexpectedException("对象转换Json字符串出错," + target.toString(), e);
}
return json;
}
}
json的赋值
function CreateJson(id,name) //JS 里面是不需要参数属性的
{
var jsonStr = {};
jsonStr.id = id;
jsonStr.name = name;
return jsonStr;
}
function UseJson()
{
var rows = []; //空JSON 数据集
for(var i=0;i变量;i++){
var id=你自己赋值;
var name=你自己赋值;
rows.push(CreateJson(id,name)); //往JSON 数据集中添加JSON 数据,原理类似 List
}
//结束后这里得到JSON数据集信息
alert(JSON.stringify(rows )); //将JSON 转化成string 输出,否则显示Object
//输出你想要的信息
}
以上纯手打!
Android 解析json问题
Android 解析json的方式为:
1、首先,搭建一个服务器的工程:JsonProject这个项目
源代码:
Person.java
package com.json.domain;
public class Person {
private int id;
private String name;
private String address;
public Person() {
super();
}
public Person(int id, String name, String addrss) {
super();
this.id = id;
this.name = name;
this.address = addrss;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [addrss=" + address + ", id=" + id + ", name=" + name
+ "]";
}
}
JsonService.java
package com.json.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.json.domain.Person;
public class JsonService {
public JsonService() {
}
public Person getPerson(){
Person person = new Person(1001,"jack","上海黄浦区");
return person;
}
public ListPerson getListPerson(){
ListPerson list = new ArrayListPerson();
Person person1 = new Person(1001,"jack","上海黄浦区");
Person person2 = new Person(1002,"rose","上海闵行区");
Person person3 = new Person(1003,"mick","上海黄浦区");
list.add(person1);
list.add(person2);
list.add(person3);
return list;
}
public ListString getListString(){
ListString list = new ArrayListString();
list.add("北京");
list.add("上海");
list.add("湖南");
return list;
}
public ListMapString,Object getListMaps(){
ListMapString,Object list = new ArrayListMapString,Object();
MapString,Object map1 = new HashMapString, Object();
MapString,Object map2 = new HashMapString, Object();
map1.put("id", 1001);
map1.put("name", "jack");
map1.put("address", "北京");
map2.put("id", 1001);
map2.put("name", "rose");
map2.put("address", "上海");
list.add(map1);
list.add(map2);
return list;
}
}
JsonServlet.java
package com.json.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.json.service.JsonService;
import com.json.tools.JsonTools;
public class JsonServlet extends HttpServlet {
private JsonService service;
/**
* Constructor of the object.
*/
public JsonServlet() {
super();
}
/**
* Destruction of the servlet. br
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. br
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
/**
* The doPost method of the servlet. br
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
String jsonString = "";
String action_flag = request.getParameter("action_flag");
if(action_flag.equals("person")){
jsonString = JsonTools.createJsonString("person", service.getPerson());
}else if(action_flag.equals("persons")){
jsonString = JsonTools.createJsonString("persons", service.getListPerson());
}else if(action_flag.equals("listString")){
jsonString = JsonTools.createJsonString("listString", service.getListString());
}else if(action_flag.equals("listMap")){
jsonString = JsonTools.createJsonString("listMap", service.getListMaps());
}
out.println(jsonString);
out.flush();
out.close();
}
/**
* Initialization of the servlet. br
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
service = new JsonService();
}
}
2、通过浏览器
访问地址一:
输出以下结果:
{"person":{"address":"上海黄浦区","id":1001,"name":"jack"}
访问地址二:
输出以下结果:
{"persons":[{"address":"上海黄浦区","id":1001,"name":"jack"},{"addrss":"上海闵行区","id":1002,"name":"rose"},{"address":"上海黄浦区","id":1003,"name":"mick"}]}
访问地址三:
输出以下结果:
{"persons":["北京","上海","湖南"]}
访问地址四:
输出以下结果:
{"persons":[{"id":1001,"address":"北京","name":"jack"},{"id":1001,"address":"上海","name":"rose"}]}
在eclipse中,如何导入json包和使用呢?
json-lib-2.3-jdk15.jar
commons-beanutils-1.7.0.jar
commons-httpclient-3.1.jar
commons-lang-2.3.jar
commons-logging-1.0.4.jar
commons-collections-3.1.jar
ezmorph-1.0.3.jar
这些包可以从一下地方下载:
如果不关联这些包,则会出现以下错误:
java.lang.NoClassDefFoundError: net/sf/ezmorph/Morpher
java.lang.NoClassDefFoundError: org/apache/commons/collections/map/ListOrderedMap
java.lang.NoClassDefFoundError: org/apache/commons/beanutils/DynaBean
java.lang.NoClassDefFoundError: org/apache/commons/codec/DecoderException
java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
使用的话
JSON Editor Plugin 是 Eclipse 下用来编辑 JSON 格式数据的插件,具有语法着色、文档结构概览、显示格式化等功能。
如何使用java创建json对象
//将数据转换为Json
public static String createJsonString(String key, Object value) {
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
Java解析json数据
一、 JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。
Json建构于两种结构:
1、“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 如:
{
“name”:”jackson”,
“age”:100
}
2、值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)如:
{
“students”:
[
{“name”:”jackson”,“age”:100},
{“name”:”michael”,”age”:51}
]
}
二、java解析JSON步骤
A、服务器端将数据转换成json字符串
首先、服务器端项目要导入json的jar包和json所依赖的jar包至builtPath路径下(这些可以到JSON-lib官网下载:)
然后将数据转为json字符串,核心函数是:
public static String createJsonString(String key, Object value)
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
}
B、客户端将json字符串转换为相应的javaBean
1、客户端获取json字符串(因为android项目中已经集成了json的jar包所以这里无需导入)
public class HttpUtil
{
public static String getJsonContent(String urlStr)
{
try
{// 获取HttpURLConnection连接对象
URL url = new URL(urlStr);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
// 设置连接属性
httpConn.setConnectTimeout(3000);
httpConn.setDoInput(true);
httpConn.setRequestMethod("GET");
// 获取相应码
int respCode = httpConn.getResponseCode();
if (respCode == 200)
{
return ConvertStream2Json(httpConn.getInputStream());
}
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
private static String ConvertStream2Json(InputStream inputStream)
{
String jsonStr = "";
// ByteArrayOutputStream相当于内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 将输入流转移到内存输出流中
try
{
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1)
{
out.write(buffer, 0, len);
}
// 将内存流转换为字符串
jsonStr = new String(out.toByteArray());
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonStr;
}
}
2、获取javaBean
public static Person getPerson(String jsonStr)
{
Person person = new Person();
try
{// 将json字符串转换为json对象
JSONObject jsonObj = new JSONObject(jsonStr);
// 得到指定json key对象的value对象
JSONObject personObj = jsonObj.getJSONObject("person");
// 获取之对象的所有属性
person.setId(personObj.getInt("id"));
person.setName(personObj.getString("name"));
person.setAddress(personObj.getString("address"));
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return person;
}
public static ListPerson getPersons(String jsonStr)
{
ListPerson list = new ArrayListPerson();
JSONObject jsonObj;
try
{// 将json字符串转换为json对象
jsonObj = new JSONObject(jsonStr);
// 得到指定json key对象的value对象
JSONArray personList = jsonObj.getJSONArray("persons");
// 遍历jsonArray
for (int i = 0; i personList.length(); i++)
{
// 获取每一个json对象
JSONObject jsonItem = personList.getJSONObject(i);
// 获取每一个json对象的值
Person person = new Person();
person.setId(jsonItem.getInt("id"));
person.setName(jsonItem.getString("name"));
person.setAddress(jsonItem.getString("address"));
list.add(person);
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}