zoukankan      html  css  js  c++  java
  • Json对象处理.将对象处理成dic数组.

    var parser = new JsonConfigurationFileParser();
    var dict = parser.Parse("json");

    using Newtonsoft.Json.Linq;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    namespace Demo
    {
    internal class JsonConfigurationFileParser
    {
    private readonly IDictionary<string, string> _data = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    private readonly Stack<string> _context = new Stack<string>();
    private string _currentPath;

    public IDictionary<string, string> Parse(string content)
    {
    _data.Clear();
    var jsonConfig = JObject.Parse(content);
    VisitJObject(jsonConfig);
    return _data;
    }

    private void VisitJObject(JObject jObject)
    {
    foreach (var property in jObject.Properties())
    {
    EnterContext(property.Name);
    VisitProperty(property);
    ExitContext();
    }
    }

    private void VisitProperty(JProperty property)
    {
    VisitToken(property.Value);
    }

    private void VisitToken(JToken token)
    {
    switch (token.Type)
    {
    case JTokenType.Object:
    VisitJObject(token.Value<JObject>());
    break;

    case JTokenType.Array:
    VisitArray(token.Value<JArray>());
    break;

    case JTokenType.Integer:
    case JTokenType.Float:
    case JTokenType.String:
    case JTokenType.Boolean:
    case JTokenType.Bytes:
    case JTokenType.Raw:
    case JTokenType.Null:
    VisitPrimitive(token);
    break;

    default:
    throw new FormatException("FormatError_UnsupportedJSONToken");
    }
    }

    private void VisitArray(JArray array)
    {
    for (int index = 0; index < array.Count; index++)
    {
    EnterContext(index.ToString());
    VisitToken(array[index]);
    ExitContext();
    }
    }

    private void VisitPrimitive(JToken data)
    {
    var key = _currentPath;

    if (_data.ContainsKey(key))
    {
    throw new FormatException("FormatError_KeyIsDuplicated");
    }
    _data[key] = data.ToString();
    }

    private void EnterContext(string context)
    {
    _context.Push(context);
    _currentPath = ConfigurationPath.Combine(_context.Reverse());
    }

    private void ExitContext()
    {
    _context.Pop();
    _currentPath = ConfigurationPath.Combine(_context.Reverse());
    }
    }
    }

  • 相关阅读:
    手把手教你实现热力图!
    [学习笔记]overthewire bandit 通关秘籍
    施乐3065复印机邮件功能调试
    [IT学习]Greatwall
    [IT学习]从网上获取pdf制作vce文件
    [办公自动化]如何选择投影仪的吊装距离
    [读书笔记]《没人会告诉你的PPT真相》
    英文主日学材料备忘
    win10访问共享文件夹提示:引用的账户当前已锁定,且当前可能无法登陆
    [IT学习]Linux 学习笔记
  • 原文地址:https://www.cnblogs.com/mailaidedt/p/7085842.html
Copyright © 2011-2022 走看看