Golang a JSON string that decodes an unknown key

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.