JAVA CODE:

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 List<Person> getListPerson(){
List<Person> list = new ArrayList<Person>();
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 List<String> getListString(){
List<String> list = new ArrayList<String>();
list.add("北京");
list.add("上海");
list.add("湖南");
return list;
} public List<Map<String,Object>> getListMaps(){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> map1 = new HashMap<String, Object>();
Map<String,Object> map2 = new HashMap<String, 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;
}
}

经过如下的JSON序列化后:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.json.bean.Person; /**
* 完成对JSON数据的解析
* @author wulianghuan
*
*/
public class JsonTools { public JsonTools() { } public static String createjsonString (String key, Object value) {
JSONObjcet jsonObject=new JSONObject();
jsonObject.put(key, value);
return jsonObject.toString();
) /**
* 获取对象数据
* @param key
* @param jsonString
* @return
*/
public static Person getPerson(String key,String jsonString){
Person person = new Person();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject personObject = jsonObject.getJSONObject(key);
person.setId(personObject.getInt("id"));
person.setName(personObject.getString("name"));
person.setAddress(personObject.getString("address"));
} catch (JSONException e) {
e.printStackTrace();
}
return person;
} /**
* 获取对象数组数据
* @param key
* @param jsonString
* @return
*/
public static List<Person> getPersons(String key,String jsonString){
List<Person> list = new ArrayList<Person>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
//返回json的数组
JSONArray jsonArray = jsonObject.getJSONArray(key);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Person person = new Person();
person.setId(jsonObject2.getInt("id"));
person.setName(jsonObject2.getString("name"));
person.setAddress(jsonObject2.getString("address"));
list.add(person);
}
} catch (JSONException e) {
e.printStackTrace();
} return list;
}
/**
* 获取String数组数据
* @param key
* @param jsonString
* @return
*/
public static List<String> getList(String key,String jsonString){
List<String> list = new ArrayList<String>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for(int i=0;i<jsonArray.length();i++){
String msg = jsonArray.getString(i);
list.add(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
/**
* 获取对象的Map集合数据
* @param key
* @param jsonString
* @return
*/
public static List<Map<String,Object>> getListMap(String key,String jsonString){
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonArray = jsonObject.getJSONArray(key);
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
Map<String,Object> map = new HashMap<String, Object>();
Iterator<String> iterator = jsonObject2.keys();
while(iterator.hasNext()){
String json_key = iterator.next();
Object json_value = jsonObject2.get(json_key);
if(json_value==null){
json_value = "";
}
map.put(json_key, json_value);
}
list.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return list;
}
}

Serlet:

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();
} }

 

每个方法返回的JSONSTR如下:

getPerson():

{"persons":{"address":"上海黄浦区","id":1001,"name":"jack"}}

getListPerson():

{"persons":[{"address":"上海黄浦区","id":1001,"name":"jack"},{"addrss":"上海闵行区","id":1002,"name":"rose"},{"address":"上海黄浦区","id":1003,"name":"mick"}]}

getListString():

{"persons":["北京","上海","湖南"]}

getListMap():

{"persons":[{"id":1001,"address":"北京","name":"jack"},{"id":1001,"address":"上海","name":"rose"}]}

 

而在.Net中对比如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections; namespace NetJSON
{
public partial class JSON : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string flag = Request["action_flag"];
string jsonStr = "";
switch (flag)
{
case "person":
var p = new Person();
p.Id = 100;
p.Name = "张三";
p.Address = "北京朝阳";
jsonStr = JsonHelper.JsonSerializer<Person>(p);
break;
case "persons":
List<Person> persons = new List<Person>();
persons.Add(new Person
{
Id = 101,
Name = "李四",
Address = "北京昌平"
});
persons.Add(new Person
{
Id = 102,
Name = "王五",
Address = "北京顺义"
});
persons.Add(new Person
{
Id = 103,
Name = "赵六",
Address = "天津南开"
});
jsonStr = JsonHelper.JsonSerializer<List<Person>>(persons);
break;
case "stringList":
List<string> strs = new List<string>();
strs.Add("china");
strs.Add("beijing");
strs.Add("chaoyang");
jsonStr = JsonHelper.JsonSerializer<List<string>>(strs);
break;
case "listMap":
List<Hashtable> listMap = new List<Hashtable>();
Hashtable ht = new Hashtable();
ht.Add("Id", 203);
ht.Add("Name", "老赵");
ht.Add("Age", 36);
listMap.Add(ht);
ht = new Hashtable();
ht.Add("Id", 204);
ht.Add("Name", "老张");
ht.Add("Age", 46);
ht.Add("Married", true);
listMap.Add(ht); List<SortedDictionary<string, object>> list = new List<SortedDictionary<string, object>>();
SortedDictionary<string, object> dict = new SortedDictionary<string, object>();
dict.Add("Id", 334);
dict.Add("Name", "XYZ");
list.Add(dict);
dict = new SortedDictionary<string, object>();
dict.Add("Id", 334);
dict.Add("Address", "XYZ");
dict.Add("Married", false);
list.Add(dict);
jsonStr = JsonHelper.JsonSerializer<List<SortedDictionary<string, object>>>(list);
break;
}
Response.Write(jsonStr);
Response.End();
}
} public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
}

JSON序列化代码:

using System.Runtime.Serialization.Json;
using System.IO;
using System.Text; namespace NetJSON
{
/// <summary>
/// JSON序列化和反序列化辅助类
/// </summary>
public class JsonHelper
{
/// <summary>
/// JSON序列化
/// </summary>
public static string JsonSerializer<T>(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return jsonString;
} /// <summary>
/// JSON反序列化
/// </summary>
public static T JsonDeserialize<T>(string jsonString)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
T obj = (T)ser.ReadObject(ms);
return obj;
}
}
}

person:

{"Address":"北京朝阳","Id":100,"Name":"张三"}

persons:

[{"Address":"北京昌平","Id":101,"Name":"李四"},{"Address":"北京顺义","Id":102,"Name":"王五"},{"Address":"天津南开","Id":103,"Name":"赵六"}]

stringList:

["china","beijing","chaoyang"]

listMap:

[[{"Key":"Id","Value":201},{"Key":"Name","Value":"老赵"}],[{"Key":"Id","Value":203},{"Key":"Birthday","Value":"\/Date(232214400000+0800)\/"},{"Key":"Married","Value":true}]]

 

注意其中.Net中Hashtable或者Dictionary返回的字符串与Java的不同。

JAVA与C#关于JSON序列化的比较的更多相关文章

  1. java编解码技术,json序列化与二进制序列化

    1.何为json序列化与二进制序列化 通常我们在程序中采用的以json为传输,将json转为对象的就是json序列化了.而二进制序列化通常是我们将数据转换为二进制进行传输,然后在进行各类转换操作 2. ...

  2. Java中常见的json序列化类库 - Jackson

    Jackson 介绍 Jackson框架是基于Java平台的一套数据处理工具,被称为"最好的Java Json解析器". Jackson框架包含了3个核心库:streaming,d ...

  3. Java中的Json序列化,不容忽视的getter

    在开发的过程中,经常会碰到和自己预期不一样的情况.有的时候自己去研究一下还是很有趣的.这两天在写java web的时候,碰到了一个对象序列化的问题. 问题重现 public class AjaxJso ...

  4. Java 的世界,我不懂:奇葩的 json 序列化

    先上张图,代表我心中的十万头草泥马: 写这么长的代码,头回见数组和单个实体共用同一个 json 节点的! 恐怕只有 java 社区的大牛B 才能做出这等事.. 由 Apache 发布: http:// ...

  5. spring mvc返回json字符串数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable

    1.spring mvc返回json数据,只需要返回一个java bean对象就行,只要这个java bean 对象实现了序列化serializeable 2. @RequestMapping(val ...

  6. Java JSON序列化杂谈

    在C#中序列化是比较容易的,如果不用第三方的类库,那么C#提供的两个对象也够我们使用,一般的操作是定义一个不含有方法的类,这个类里面定义了要序列化的对象的属性,因为我C#用的比较多,这里直接给出泛型, ...

  7. Java下用Jackson进行JSON序列化和反序列化(转)

    Java下常见的Json类库有Gson.JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的J ...

  8. java对象json序列化时忽略值为null的属性

    环境: jdk: openjdk11 操作系统: windows 10教育版1903 目的: 如题,当一个对象里有些属性值为null 的不想参与json序列化时,可以添加如下注解 import com ...

  9. NetworkComms V3 使用Json序列化器进行网络通信

    刚才在网上闲逛,偶然看到一篇文章 C#(服务器)与Java(客户端)通过Socket传递对象 网址是:http://www.cnblogs.com/iyangyuan/archive/2012/12/ ...

随机推荐

  1. System.Threading.Timer 使用

    //定义计时器执行完成后的回调函数 TimerCallback timecallback = new TimerCallback(WriteMsg); //定义计时器 System.Threading ...

  2. quartz 的学习和使用。

    任务调度器, 定时任务,保存好后会被放入触发器,这些触发器被存入到数据库,调度器线程扫描,如果有待触发的打开锁,拿到job信息,更改trigger信息,释放锁,返回所有的trigger列表,再 按照时 ...

  3. htaccess URL重写rewrite与重定向redirect(转)

    1. 将 .htm 页面映射到 .php 1 Options +FollowSymlinks 2 RewriteEngine on 3 RewriteRule ^(.*)\.htm$ $1.php [ ...

  4. Java面试求职之==与equals()差别

    Java中equals和==的差别 java中的数据类型,可分为两类:     1.基本数据类型(也称原始数据类型):byte,short,char,int,long,float,double,boo ...

  5. PHP 計算字符串長度函數

    PHP內置的字符串長度函數strlen無法正確處理中文字符串,它得到的只是字符串所占的字節數.對於GB2312的中文編碼,strlen得到的值是漢字個數的2倍,而對於UTF-8編碼的中文,就是3倍的差 ...

  6. Java基础知识强化之集合框架笔记04:Collection集合的基本功能测试

    1. Collection集合的基本功能测试: package cn.itcast_01; import java.util.ArrayList; import java.util.Collectio ...

  7. Windows下Android Studio长时间停留在Building "Project Name" Gradle project info画面的解决方法

    问题描述: 创建好一个Android项目后,Android Studio长时间停留在Building [Project Name] Gradle project info画面不动. 原因: 此时And ...

  8. codevs 1282 约瑟夫问题(线段树)

    #include<iostream> #include<cstdio> #include<cstring> #define maxn 30010 using nam ...

  9. JavaScript自动关闭窗口

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  10. C#_事件委托

    CarDealer类 事件发布程序 using System; using System.Collections.Generic; using System.Linq; using System.Te ...