We can use interface to receive JSON. Unmarshal, and then uses the type assertion attribute for subsequent operations.
Package Mainimport ("Encoding/json" "FMT") func main () {b: = []byte (' {"Name": "Wednesday", "Age": 6, "parents": ["Gomez", " Morticia "]} ') var f interface{}json. Unmarshal (b, &f) M: = f. (map[string]interface{}) fmt. Println (m["parents"]) //Read JSON content FMT. Println (m["a"] = nil)//Determine if the key exists}
The purpose of this type assertion is to convert object objects similar to those in Java into a specific object, such as the following example:
Import Java.util.arraylist;public class Main {public static void Main (string[] args) { ArrayList ArrayList = new Arraylist<integer> (); ArrayList arrayList1 = (ArrayList) (New Test<> ()). Test (ArrayList); Arraylist1.add (1); System.out.println (ArrayList1); }} Class Test<t> {public T Test (T t) { return T; }}
The above ArrayList ArrayList1 = (ArrayList) (New Test<> ()). Test (ArrayList); In this line, we know explicitly that the function return value is the ArrayList type, so we can add (ArrayList) to the type conversion.
and Golang only the wording is not the same, Golang is the way of writing is v. (XXX), the role is to interface{} type of variable as XXX type use.
Golang a JSON string that decodes an unknown key