Map generates JSON after sorting by insert order
Last Update:2018-03-19
Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. Similar to Java Linkedhashmap, the output JSON string is sorted by key in the order of insertion <br><br>#### a Java project, refactoring to go an interface returned by a data structure is agreed with the client, there are collation The result is a map-to-string that is sorted by key insertion Order (Java can be used directly with linkedhashmap<string, OBJECT> and then JSON) <br><br>#### source "' Gopackage mainimport (" FMT "" Strings "" Encoding/json ") type Smap []*sortmapnodetype sortmapnode struct {Key stringval Interface{}}func (c *smap) Put (key string, Val interface{}) {index, _, OK: = C.get (key) if OK {(*c) [index]. val = val} else {node: = &sortmapnode{key:key, val:val}*c = append (*c, node)}}func (c *smap) Get (Key string) (Interf ace{}, BOOL) {_, val, ok: = C.get (key) return Val, Ok}func (c *smap) get (key string) (int, interface{}, BOOL) {for index, n Ode: = Range *c {if node. Key = = key {return index, node. Val, true}}return-1, Nil, False}func Tosortedmapjson (SMAP *smap) string {s: = "{" For _, Node: = Range *smap {V: = node. Valissamp: = falsestr: = "" Switch v. (type) {case *smap:issamp = true str = Tosortedmapjson (V. (*SMAP))}if (!isSamp) {B, _: = json. Marshal (node. Val) str = string (b)}s = FMT. Sprintf ("%s\"%s\ ":%s,", s, node.) Key, str)}s = strings. TrimRight (S, ",") s = fmt. Sprintf ("%s}", s) return s}type teststruct struct{name stringvalue interface{}}func Main () {SMAP: = &smap{}n1: = []int{ 5, 6}n2: = []string{"S3", "S4"}n3: = []string{"S1", "s2"}n4: = []interface{}{"a", 5,6.7}n4 = Append (N4, "t") N4 = Append (N4, 1) N4 = Append (N4, 3.2) S1: = &smap{}s1. Put ("First", "1str") s1. Put ("Second", "2str") s1. Put ("Third", "3str") s2: = &smap{}var t2 teststructt2.name = "testname" T2.value = s2s2. Put ("S1", S1) arr2: = []string{"str1", "str2"}s2. Put ("arr2", arr2) SMAP. Put ("1int", N1) SMAP. Put ("2string", N2) SMAP. Put ("3string", N3) SMAP. Put ("4interface", N4) SMAP. Put ("5smap", S1) SMAP. Put ("6interfaceSmap", s2) S: = Tosortedmapjson (SMAP) fmt. Println (s)} "# # # # # # # of results (formatted JSON) ' json{" 1int ": [5, 6]," 2string ": [" S3 "," S4 "]," 3string ": [" S1 "," S2 "]," 4interface " : ["A", 5, 6.7, "T", 1, 3.2], "5smap": {"First": "1str", "second": "2str", "third": "3str "}," 6interfaceSmap ": {" S1 ": {" First ":" 1str "," second ":" 2str "," third ":" 3str "}," arr2 ": [" str1 "," STR2 "]}}" 271 Second Click