Generically Flatten Json using c#

前端 未结 7 1686
闹比i
闹比i 2020-11-30 02:21

I want to generically flatten some json so I can convert to a datatable and bind to a datagrid using c#

What is the best way of doign it, bearing in mind I dont know

7条回答
  •  遥遥无期
    2020-11-30 03:20

    For those who need same in F#:

    module JsonFlatten =
    
    let Join prefix name =
        if String.IsNullOrEmpty(prefix) then name else prefix + "." + name
    
    let rec FillDictionaryFromJToken (dict:Dictionary) (token:JToken) (prefix:string) =
        match token.Type with
        | JTokenType.Object ->
            for prop in token.Children() do
                FillDictionaryFromJToken dict prop.Value (Join prefix prop.Name)
        | JTokenType.Array ->
            let mutable index = 0
    
            for value in token.Children() do
                FillDictionaryFromJToken dict  value (Join prefix (index.ToString()))
                index <- index + 1
        | _ ->
            dict.Add(prefix, sprintf "%A" (token :?> JValue).Value)
    
    let DeserializeAndFlatten(json:string) =
        let dict = Dictionary()
        let token = JToken.Parse(json);
        FillDictionaryFromJToken dict  token ""
        dict
    

提交回复
热议问题