zoukankan      html  css  js  c++  java
  • golang 解码未知键的 json 字符串

    我们可以使用 interface 接收 json.Unmarshal 的结果,然后利用 type assertion 特性来进行后续操作。

    package main
    
    import (
    	"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"])  // 读取 json 内容 
    	fmt.Println(m["a"] == nil) // 判断键是否存在
    }
    

      

    这个 type assertion 的作用是类似于 java 中的 Object 对象转换成某种具体的对象,好比如下面的例子:

    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;
        }
    }
    

      上面的  ArrayList arrayList1 = (ArrayList) (new Test<>()).test(arrayList);  这一行,我们明确的知道函数返回值是 ArrayList 类型,所以我们可以加上 (ArrayList) 进行类型转换。

    而 golang 中只是写法不一样而已,golang 的写法是 v.(xxx),作用是把 interface{} 类型的变量当作 xxx 类型使用。

     
  • 相关阅读:
    cqyz oj | 单峰排列
    cqyz oj/uva 548 | 二叉树
    cqyz oj | 树网的核 | 树的直径
    cqyz oj | 树上的询问 | 最近公共祖先
    cqyz oj | 循环逆序对 | 逆序对 | 树状数组
    cqyz oj | 潜水比赛 | 贪心
    YOLO v3 & Pascal VOC数据集
    太阳爆发分类
    PPT制作
    anaconda
  • 原文地址:https://www.cnblogs.com/eleven24/p/9192884.html
Copyright © 2011-2022 走看看