JsonHelper MergeJsonTemplate


namespace Test
{
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using Microshaoft;
    using Newtonsoft.Json.Linq;
    class Program
    {
        static void Main(string[] args)
        {
            string json = @"
{ a: [{a:'asdasd',b:2222},{a:'@a.[2].a'},{a:'ssss'}]}
";
            string json2 = @"
{a:['asdasd','aaaa',{a:1111}]}
";
            Console.WriteLine
                        (
                            JsonHelper
                                .MergeJsonTemplate
                                    (
                                        json
                                        , json2
                                    )
                        );
            Console.ReadLine();
        }
        static void Main2(string[] args)
        {
            string json = @"{ 'name10': 
'Admin' }
[{ 'name9': 'Publisher' }][
{ 'name4': 'Admin' },{ 'name8': ['Admin'] }]{ 'name7': 
'Admin' }
[{ 'name3': ['Publisher','Publisher'] }]{ 'name5': 
'Admin' }
[{ 'name2': 'Publisher' }]{ 'name6': 
'Admin' }
[{ 'name1': 'Publisher' }]";
            JsonTextReader reader = new JsonTextReader(new StringReader(json));
            var r = reader.ReadAllMultipleContentsAsEnumerable<JObject>().ToArray();
            reader = new JsonTextReader(new StringReader(json));
            r = reader
                    .ReadMultipleContentsAsEnumerable<JObject>(3)
                    .SelectMany
                        (
                            (x) =>
                            {
                                return x;
                            }
                        ).ToArray();
            Console.ReadLine();
        }
        static void Main1(string[] args)
        {
            string json = @"{ 'name': 
'Admin',c:1111111 }
[{ 'name': 'Publisher' }][
{ 'name': 'Admin' },{ 'name': 'Admin' }]{ 'name': 
'Admin' }
[{ 'name': 'Publisher' }]{ 'name': 
'Admin' }
[{ 'name': 'Publisher' }]{ 'name': 
'Admin' }
[{ 'name': 'Publisher' }]";
            IList<Role> roles = new List<Role>();
            JsonTextReader reader = new JsonTextReader(new StringReader(json));
            var r = reader.ReadAllMultipleContentsAsEnumerable<Role>().ToArray();
            reader = new JsonTextReader(new StringReader(json));
            r = reader
                    .ReadMultipleContentsAsEnumerable<Role>(3)
                    .SelectMany
                        (
                            (x) =>
                            {
                                return x;
                            }
                        ).ToArray();
            Console.ReadLine();
        }
    }
    public class Role
    {
        public string Name { get; set; }
    }
}
namespace Microshaoft
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System;
    using System.IO;
    using System.Linq;
    using System.Xml.Linq;
    using System.Collections.Generic;
    public static class JsonHelper
    {
        public static JToken MergeJsonTemplateToJToken
                        (
                            string jsonTemplate
                            , string jsonData
                            , string jsonTemplatePathPrefix = "@"
                        )
        {
            var jTokenTemplate = JToken.Parse(jsonTemplate);
            var jTokenData = JToken.Parse(jsonData);
            JsonReaderHelper
                    .ReadAllPaths
                        (
                            jsonTemplate
                            , (isJArray, jsonPath, valueObject, valueType, reader) =>
                            {
                                var vs = valueObject as string;
                                if (vs != null)
                                {
                                    vs = vs.Trim();
                                    if (vs.StartsWith(jsonTemplatePathPrefix))
                                    {
                                        var replacedSelectToken = jTokenTemplate.SelectToken(jsonPath);
                                        var trimChars = jsonTemplatePathPrefix.ToCharArray();
                                        vs = vs.TrimStart(trimChars);
                                        var replacementSelectToken = jTokenData.SelectToken(vs);
                                        replacedSelectToken.Replace(replacementSelectToken);
                                    }
                                }
                                return false;
                            }
                        );
            return jTokenTemplate;
        }
        public static string MergeJsonTemplate
                (
                    string jsonTemplate
                    , string jsonData
                    , string jsonTemplatePathPrefix = "@"
                )
        {
            return
                    MergeJsonTemplateToJToken
                                (
                                    jsonTemplate
                                    , jsonData
                                    , jsonTemplatePathPrefix
                                )
                                .ToString();
        }
        public static string XmlToJson
                                (
                                    string xml
                                    , Newtonsoft
                                            .Json
                                            .Formatting formatting
                                                            = Newtonsoft
                                                                    .Json
                                                                    .Formatting
                                                                    .Indented
                                    , bool needKeyQuote = false
                                )
        {
            XNode xElement;
            xElement = XElement.Parse(xml).Elements().First();
            string json = string.Empty;
            using (var stringWriter = new StringWriter())
            {
                using (var jsonTextWriter = new JsonTextWriter(stringWriter))
                {
                    jsonTextWriter.Formatting = formatting;
                    jsonTextWriter.QuoteName = needKeyQuote;
                    var jsonSerializer = new JsonSerializer();
                    jsonSerializer.Serialize(jsonTextWriter, xElement);
                    json = stringWriter.ToString();
                }
            }
            return json;
        }
        public static string JsonToXml
                        (
                            string json
                            , bool needRoot = false
                            , string defaultDeserializeRootElementName = "root"
                        )
        {
            if (needRoot)
            {
                json = string.Format
                                (
                                    @"{{ {1}{0}{2} }}"
                                    , " : "
                                    , defaultDeserializeRootElementName
                                    , json
                                );
            }
            //XmlDocument xmlDocument = JsonConvert.DeserializeXmlNode(json, defaultDeserializeRootElementName);
            var xDocument = JsonConvert
                                    .DeserializeXNode
                                        (
                                            json
                                            , defaultDeserializeRootElementName
                                        );
            var xml = xDocument
                            .Elements()
                            .First()
                            .ToString();
            return xml;
        }
        public static T DeserializeByJTokenPath<T>
            (
                string json
                , string jTokenPath = null //string.Empty
            )
        {
            var jObject = JObject.Parse(json);
            var jsonSerializer = new JsonSerializer();
            if (string.IsNullOrEmpty(jTokenPath))
            {
                jTokenPath = string.Empty;
            }
            var jToken = jObject.SelectToken(jTokenPath);
            using (var jsonReader = jToken.CreateReader())
            {
                return
                    jsonSerializer
                        .Deserialize<T>(jsonReader);
            }
        }
        public static string Serialize
                                (
                                    object target
                                    , bool formattingIndented = false
                                    , bool keyQuoteName = false
                                )
        {
            string json = string.Empty;
            using (StringWriter stringWriter = new StringWriter())
            {
                using (var jsonTextWriter = new JsonTextWriter(stringWriter))
                {
                    jsonTextWriter.QuoteName = keyQuoteName;
                    jsonTextWriter.Formatting = (formattingIndented ? Formatting.Indented : Formatting.None);
                    var jsonSerializer = new JsonSerializer();
                    jsonSerializer.Serialize(jsonTextWriter, target);
                    json = stringWriter.ToString();
                }
            }
            return json;
        }
        public static void ReadJsonPathsValuesAsStrings
                            (
                                string json
                                , string[] jsonPaths
                                , Func<string, string, bool> onReadedOncePathStringValueProcesssFunc = null
                            )
        {
            using (var stringReader = new StringReader(json))
            {
                using (var jsonReader = new JsonTextReader(stringReader))
                {
                    bool breakAndReturn = false;
                    while
                        (
                            jsonReader.Read()
                            &&
                            !breakAndReturn
                        )
                    {
                        foreach (var x in jsonPaths)
                        {
                            if (x == jsonReader.Path)
                            {
                                if (onReadedOncePathStringValueProcesssFunc != null)
                                {
                                    var s = jsonReader.ReadAsString();
                                    breakAndReturn
                                            = onReadedOncePathStringValueProcesssFunc
                                                    (
                                                        x
                                                        , s
                                                    );
                                    if (breakAndReturn)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        public static IEnumerable<TElement>
                            DeserializeToFromDictionary<TKey, TValue, TElement>
                                        (
                                            string json
                                            , Func<TKey, TValue, TElement> OnOneElementProcessFunc
                                        )
        {
            //IEnumerable<TElement> r = default(IEnumerable<TElement>);
            return
                    DeserializeByJTokenPath<Dictionary<TKey, TValue>>(json)
                        .Select
                            (
                                (x) =>
                                {
                                    var rr = OnOneElementProcessFunc(x.Key, x.Value);
                                    return rr;
                                }
                            );
            //return r;
        }
    }
}
namespace Microshaoft
{
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Collections.Generic;
    using System;
    using System.IO;
    public static class JsonReaderHelper
    {
        public static void ReadAllPaths
                    (
                        string json
                        , Func<bool, string, object, Type, JsonReader, bool> onReadPathOnceProcessFunc
                    )
        {
            using (JsonReader reader = new JsonTextReader(new StringReader(json)))
            {
                var isStarted = false;
                var isJArray = false;
                while (reader.Read())
                {
                    JsonToken tokenType = reader.TokenType;
                    if (!isStarted)
                    {
                        if (tokenType == JsonToken.StartArray)
                        {
                            isJArray = true;
                            isStarted = true;
                        }
                        else if (tokenType == JsonToken.StartArray)
                        {
                            isStarted = true;
                        }
                        else if (tokenType == JsonToken.StartConstructor)
                        {
                            isStarted = true;
                        }
                    }
                    if
                        (
                            tokenType != JsonToken.Comment
                            &&
                            tokenType != JsonToken.PropertyName
                        )
                    {
                        var jsonPath = reader.Path;
                        if (!string.IsNullOrEmpty(jsonPath))
                        {
                            var valueType = reader.ValueType;
                            var valueObject = reader.Value;
                            if (valueType != null)
                            {
                                var r = onReadPathOnceProcessFunc
                                                (
                                                    isJArray
                                                    , jsonPath
                                                    , valueObject
                                                    , valueType
                                                    , reader
                                                );
                                if (r)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
                reader.Close();
            }
        }
        public static void ReadAllMultipleContents
                                        (
                                            this JsonReader target
                                        )
        {
            if (!target.SupportMultipleContent)
            {
                target.SupportMultipleContent = true;
            }
            var serializer = new JsonSerializer();
            //serializer.CheckAdditionalContent
            while (target.Read())
            {
                Console.WriteLine(target.TokenType);
                var r = serializer.Deserialize(target);
                Console.WriteLine(r.GetType());
                Console.WriteLine(r.ToString());
            }
        }
        public static IEnumerable<JToken> ReadMultipleContents
                                                (
                                                    this JsonReader target
                                                )
        {
            if (!target.SupportMultipleContent)
            {
                target.SupportMultipleContent = true;
            }
            var serializer = new JsonSerializer();
            while (target.Read())
            {
                if (target.TokenType == JsonToken.StartObject)
                {
                    JToken entry = serializer.Deserialize<JToken>(target);
                    yield return entry;
                }
                else if (target.TokenType == JsonToken.StartArray)
                {
                    JArray entries = serializer.Deserialize<JArray>(target);
                    foreach (var entry in entries)
                    {
                        if (entry is JArray)
                        {
                            //Console.WriteLine();
                        }
                        yield return (JToken)entry;
                    }
                }
            }
        }
        public static IEnumerable<IEnumerable<T>> ReadMultipleContentsAsEnumerable<T>
                        (
                            this JsonReader target
                            , int pageSize = 10
                        )
        {
            if (!target.SupportMultipleContent)
            {
                target.SupportMultipleContent = true;
            }
            var serializer = new JsonSerializer();
            var list = new List<T>();
            var i = 0;
            while (target.Read())
            {
                if (target.TokenType == JsonToken.StartArray)
                {
                    var entries = serializer.Deserialize<T[]>(target);
                    foreach (var entry in entries)
                    {
                        if (i < pageSize)
                        {
                            i++;
                            list.Add(entry);
                        }
                        if (i >= pageSize)
                        {
                            yield return list;
                            list.Clear();
                            i = 0;
                        }
                    }
                }
                else
                {
                    var entry = serializer.Deserialize<T>(target);
                    if (i < pageSize)
                    {
                        i++;
                        list.Add(entry);
                    }
                    if (i >= pageSize)
                    {
                        yield return list;
                        list.Clear();
                        i = 0;
                    }
                }
            }
            if (i > 0)
            {
                yield return list;
                list.Clear();
                i = 0;
                list = null;
            }
        }
        public static IEnumerable<T> ReadAllMultipleContentsAsEnumerable<T>(this JsonReader target)
        {
            if (!target.SupportMultipleContent)
            {
                target.SupportMultipleContent = true;
            }
            var serializer = new JsonSerializer();
            while (target.Read())
            {
                if (target.TokenType == JsonToken.StartArray)
                {
                    var entries = serializer.Deserialize<T[]>(target);
                    foreach (var entry in entries)
                    {
                        yield return entry;
                    }
                }
                else
                {
                    var entry = serializer.Deserialize<T>(target);
                    yield return entry;
                }
            }
        }
    }
}

posted @ 2016-12-10 20:06  于斯人也  阅读(699)  评论(0编辑  收藏  举报