server-side output JSON format data
Here we discuss how to output JSON-formatted data on the server side. In Java, for example, we will demonstrate the encoding of a Java object into JSON-formatted text.
When you encode a String object in JSON format, you only need to handle the special characters. In addition, the string must be represented by ( "
) rather than ( ‘
):
static String String2json ( String s) {StringBuilder sb = new StringBuilder (s.length () +20); Sb.append (' \ '); for (int i=0; i<s.length (); i++) {char c = s.charat (i); Switch (c) {case ' \ ': Sb.append ("\\\"); Break Case ' \ \ ': Sb.append ("\\\\"); Break Case '/': Sb.append ("\\/"); Break Case ' \b ': sb.append ("\\b"); Break Case ' \f ': Sb.append ("\\f"); Break Case ' \ n ': sb.append ("\\n"); Break Case ' \ R ': Sb.append ("\\r"); Break Case ' \ t ': Sb.append ("\\t"); Break Default:sb.append (c); }} sb.append (' \ "'); return sb.tostring (); } |
It is much easier to represent number as JSON, and with Java polymorphism, we can deal with integer,long,float, and so on.
Static String Number2json (number number) { return number.tostring (); |
The Boolean type can also be used to toString()
get the JSON representation directly from the method:
Static String Boolean2json (Boolean bool) { return bool.tostring (); } |
To encode an array into JSON format, you can encode each element through a loop:
Static String Array2json (object[] array) { if (array.length==0) return "[]"; StringBuilder sb = new StringBuilder (Array.Length << 4); Sb.append (' ['); for (Object o:array) { sb.append (ToJson (o)); Sb.append (', '); } The last added ', ' changed to '] ': Sb.setcharat (Sb.length ()-1, '] '); return sb.tostring (); |
Finally, we need to map<string, Object>
encoded in JSON format because The JavaScript Object actually corresponds to the Java map<string, Object>
. The method is as follows:
static String Map2json (map<string, object> Map) { if (Map.isempty ()) return "{}"; StringBuilder sb = new StringBuilder (Map.size () << 4); Sb.append (' {'); set<string> keys = Map.keyset (); for (String Key:keys) { Object value = Map.get (key); Sb.append (' \ '); Sb.append (key); Sb.append (' \ '); Sb.append (': '); Sb.append (ToJson (value)); Sb.append (', '); } Sb.setcharat (Sb.length ()-1, '} '); return sb.tostring (); |
To unify the processing of arbitrary Java objects, we write an ingress method toJson(Object)
that encodes any Java object into JSON format:
public static String ToJson (Object o) { if (o==null) return "null"; if (o instanceof string) return String2json ((String) o); if (o instanceof Boolean) return Boolean2json ((Boolean) o); if (o instanceof number) return Number2json ((number) o); if (o instanceof Map) return Map2json ((map<string, object>) o); if (o instanceof object[]) return Array2json ((object[)) o); throw new RuntimeException ("Unsupported type:" + O.getclass (). GetName ()); } |
We do not have strict checks on Java objects. Objects that are not supported (such as List) will throw runtimeexception directly. In addition, to ensure that the output JSON is valid, the Map<String, Object>
object's Key cannot contain special characters. The attentive reader may also find that the loop-referenced object throws infinite recursion, for example, by carefully constructing a Map with a circular reference, you can detect StackOverflowException
:
@Test (expected=stackoverflowerror.class) public void Testrecurrsivemap2json () { map<string, object> Map = new hashmap<string, object> (); Map.put ("key", map); Jsonutil.map2json (map); } |
Fortunately, the JSON data processed by the server should eventually be converted into simple JavaScript objects, so the likelihood of recursive referencing is minimal.
Finally, when you output JSON through a Servlet or MVC framework, you need to set the correct MIME type (Application/json) and character encoding. Assuming that the server uses UTF-8 encoding, you can output the encoded JSON text using the following code:
Response.setcontenttype ("Application/json;charset=utf-8"); Response.setcharacterencoding ("UTF-8"); PrintWriter pw = Response.getwriter (); Pw.write (Jsonutil.tojson (obj)); Pw.flush (); |
Summary
JSON is already part of the JavaScript standard. Currently, the mainstream browser is perfect for JSON support. Using JSON, we can get rid of the parsing of XML, and for those Web 2.0 Web sites that apply Ajax, JSON is really the most flexible lightweight solution available today.
JSON Format (1)