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"," Huangpu District, Shanghai ");
return person;
}
public List<Person> getListPerson(){
List<Person> list = new ArrayList<Person>();
Person person1 = new Person(1001,"jack"," Huangpu District, Shanghai ");
Person person2 = new Person(1002,"rose"," Minhang District, Shanghai ");
Person person3 = new Person(1003,"mick"," Huangpu District, Shanghai ");
list.add(person1);
list.add(person2);
list.add(person3);
return list;
} public List<String> getListString(){
List<String> list = new ArrayList<String>();
list.add(" Beijing ");
list.add(" Shanghai ");
list.add(" hunan ");
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", " Beijing ");
map2.put("id", 1001);
map2.put("name", "rose");
map2.put("address", " Shanghai ");
list.add(map1);
list.add(map2);
return list;
}
}

After the following JSON After serialization :

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; /**
* Finish right JSON Data analysis
* @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();
) /**
* Get object data
* @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;
} /**
* Get object array data
* @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);
// return json Array of
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;
}
/**
* obtain String Array data
* @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;
}
/**
* Get the object's Map Aggregate data
* @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();
} }

 

Each method returns JSONSTR as follows :

getPerson():

{"persons":{"address":" Huangpu District, Shanghai ","id":1001,"name":"jack"}}

getListPerson():

{"persons":[{"address":" Huangpu District, Shanghai ","id":1001,"name":"jack"},{"addrss":" Minhang District, Shanghai ","id":1002,"name":"rose"},{"address":" Huangpu District, Shanghai ","id":1003,"name":"mick"}]}

getListString():

{"persons":[" Beijing "," Shanghai "," hunan "]}

getListMap():

{"persons":[{"id":1001,"address":" Beijing ","name":"jack"},{"id":1001,"address":" Shanghai ","name":"rose"}]}

 

And in the .Net The comparison is as follows :

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 = " Zhang San ";
p.Address = " Beijing chaoyang ";
jsonStr = JsonHelper.JsonSerializer<Person>(p);
break;
case "persons":
List<Person> persons = new List<Person>();
persons.Add(new Person
{
Id = 101,
Name = " Li Si ",
Address = " Beijing changping "
});
persons.Add(new Person
{
Id = 102,
Name = " Wang Wu ",
Address = " Shunyi, Beijing "
});
persons.Add(new Person
{
Id = 103,
Name = " Zhao Liu ",
Address = " Tianjin Nankai "
});
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", " laozhao ");
ht.Add("Age", 36);
listMap.Add(ht);
ht = new Hashtable();
ht.Add("Id", 204);
ht.Add("Name", " Lao zhang ");
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 Serialization code :

using System.Runtime.Serialization.Json;
using System.IO;
using System.Text; namespace NetJSON
{
/// <summary>
/// JSON Serializing and deserializing helper classes
/// </summary>
public class JsonHelper
{
/// <summary>
/// JSON serialize
/// </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 Deserialization
/// </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":" Beijing chaoyang ","Id":100,"Name":" Zhang San "}

persons:

[{"Address":" Beijing changping ","Id":101,"Name":" Li Si "},{"Address":" Shunyi, Beijing ","Id":102,"Name":" Wang Wu "},{"Address":" Tianjin Nankai ","Id":103,"Name":" Zhao Liu "}]

stringList:

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

listMap:

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

 

Pay attention to .Net in Hashtable perhaps Dictionary The string returned is the same as Java Different .

JAVA And C# About JSON More articles on serialization comparison

  1. java Codec technology ,json Serialization and binary serialization

    1. What is the json Serialization and binary serialization Usually we use in the program to json For transmission , take json What becomes the object is json Serialized . And binary serialization is usually that we transform data into binary for transmission , And then in all kinds of conversion operations 2. ...

  2. Java Common in json Serialization class library - Jackson

    Jackson Introduce Jackson The framework is based on Java A set of data processing tools for the platform , go by the name of " first-class Java Json Parser ". Jackson The framework contains 3 A core library :streaming,d ...

  3. Java Medium Json serialize , Not to be ignored getter

    In the process of development , I often encounter situations that are different from my expectations . Sometimes it's interesting to study it by yourself . I've been writing these two days java web When , We ran into an object serialization problem . Problem recurrence public class AjaxJso ...

  4. Java The world of , I didn't get it. : Wonderful json serialize

    On the first picture , On behalf of the 100000 grass mud horses in my heart : Writing such a long code , Look back, arrays and single entities share the same json Node ! I'm afraid it's just java The bull of the community B To do such a thing .. from Apache Release : http:// ...

  5. spring mvc return json String data , Just return one java bean The object is , As long as the java bean Object implements serialization serializeable

    1.spring mvc return json data , Just return one java bean The object is , As long as the java bean Object implements serialization serializeable 2. @RequestMapping(val ...

  6. Java JSON I don't know

    stay C# It's easier to serialize in , If you don't use a third-party class library , that C# The two objects provided are enough for us to use , The general operation is to define a class without methods , This class defines the properties of the object to be serialized , Because of me C# It's used a lot , Let's give generics directly , ...

  7. Java Next use Jackson Conduct JSON Serialization and deserialization ( turn )

    Java The next common Json The class library has Gson.JSON-lib and Jackson etc. ,Jackson Relatively efficient , It is mainly used in the project Jackson Conduct JSON and Java Object conversion , Here are some Jackson Of J ...

  8. java object json The value of... Is ignored when serializing null Properties of

    Environmental Science : jdk: openjdk11 operating system : windows 10 Education 1903 Purpose : As the title , When some attribute values in an object are null Don't want to participate json Serialization , You can add the following comments import com ...

  9. NetworkComms V3 Use Json The serializer communicates over the network

    Just hanging out on the Internet , Come across an article C#( The server ) And Java( client ) adopt Socket Transfer object The address is :http://www.cnblogs.com/iyangyuan/archive/2012/12/ ...

Random recommendation

  1. Gesture estimation - Hand Pose Estimation

    http://blog.csdn.net/myarrow/article/details/51933651 1. Current progress 1.1 Related information      1)HANDS CVPR 2016      2 ...

  2. C++ Overload input stream review

    C++ Overload input stream #include <bits/stdc++.h> using namespace std; struct Point { int x, y; Point(int xx, ...

  3. Servo motor &amp; Resolver &amp; Photoelectric encoder

    Resolver and photoelectric encoder are the most widely used measurement sensors in servo field . One . servo system Also known as servo system , A feedback system that accurately follows or repeats a process . Position an object . bearing . State and other output controlled variables can follow the target ( Set up ) The random change of self ...

  4. The deployment environment ( 3、 ... and ):Linux Lower installation Git

    Git Is an open source distributed version control system , Can be effectively . High speed processing from very small to very large project version management , Is currently the most widely used version management tool . This blog , introduce Linux Lower installation Git Steps for , For reference only , Of course , still yum install ...

  5. mobile adaptor &amp; css media query

    mobile adaptor & css media query Mobile adaptation & Media query http://cssmediaqueries.com/ device-aspect-rati ...

  6. Bing The dictionary vs You Dao dictionary comparison test report —— The auxiliary function of function chapter , Differentiation function and software efficiency

    1. Auxiliary function : Compared with Youdao , Bing's Dictionary Adds skin changing function , Users can choose their favorite colors , And Bing has more skin , This design adds a lot of color to Bing . Relatively speaking , Youdao is added to adjust the font size of the client , as follows , It's also more humane 2. Bad ...

  7. sysctl.conf File,

    In this paper, from :http://www.cnblogs.com/Rosanna/p/3446557.html Order to make a document effective immediately :/sbin/sysctl -p /proc/sys Most kernel parameters are stored in the directory , ...

  8. linux Diagram of common cloud operation and maintenance monitoring tools

    With the development of new technology , Cloud services have become a must for Internet companies , But there will be traditional physical hosts and cloud hosts for a long time . The coexistence of private cloud and public cloud . Besides , The development speed of Internet enterprises is very fast , millet . Didi travel and many other enterprises have developed in just a few years ...

  9. MyBatis The use of framework and source code analysis ( 5、 ... and ) DefaultSqlSessionFactory and DefaultSqlSession

    We review <MyBatis In the frame Mapper Use and principle analysis of mapping configuration ( One ) Configuration and use > An example of an article private static SqlSessionFactory getSessionF ...

  10. Share a few based on Yii2 Open source projects for

    Yii2 Starter Kit(Yii2 Open the box ):https://github.com/trntv/yii2-starter-kit GetYii:https://github.com/iiYi ...