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

时间: 2024-12-15 01:42:11

JsonHelper MergeJsonTemplate的相关文章

【C#公共帮助类】JsonHelper 操作帮助类, 以后再也不用满地找Json了,拿来直接用

 四个主要操作类:JsonConverter .JsonHelper .JsonSplit .AjaxResult 一.JsonConverter: 自定义查询对象转换动态类.object动态类转换json包.json转换object动态类.DataReader转换为Json.DataSet转换为Json.DataTable转成Json.Datatable转换为Json .格式化字符型日期型布尔型.过滤特殊字符等 using System; using System.Collections.Ge

JsonHelper

.net下的json序列化在以前没有Newtonsoft.Json崭露头角之前采用System.Web.Script.Serialization命名空间下的JavaScriptSerializer对象进行序列化和反序列化的操作,随着Newtonsoft.Json的出现和优越的性能表现基本成为.net下的首选. Newtonsoft.json自身已经提供了丰富的API,让序列化变得简单和易用.项目中喜欢封装一些helper,在原有基于JavaScriptSerializer基础上稍加改造即可完成j

JsonHelper修改4.0

public class JsonHelper { /// <summary> /// 将对象序列化为JSON格式 /// </summary> /// <param name="o">对象</param> /// <returns>json字符串</returns> public static string SerializeObject(object o) { string json = JsonConvert

C# JsonHelper 操作辅助类,拿来直接用

四个主要操作类:JsonConverter .JsonHelper .JsonSplit .AjaxResult 一.JsonConverter: 自定义查询对象转换动态类.object动态类转换json包.json转换object动态类.DataReader转换为Json. DataSet转换为Json.DataTable转成Json.Datatable转换为Json .格式化字符型日期型布尔型.过滤特殊字符等 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

c# 上的JsonHelper

using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; namespace Helper { public static class JsonHelper { /// <summary> /// List转成json /// </sum

JavaScriptSerializer的实现-常用JsonHelper类

最近开始自己写自己的项目了,终于鼓起勇气迈出了自己认为的这一大步! 先来通用的helper类和大家分享一下 ,第一个是Object转为json序列的类,这个网上有很多,但我实践了一下大部分都不能用的,或者有各种bug,其实C#中有一个很好的类可以解决这个问题,他就是--JavaScriptSerializer类,有了这个类,只需简单的几行代码,就可以把你的object类型转化成json往前台输出了! 首先我们要在项目中引用 System.Web.Extensions这个dll,才可以使用Java

JsonHelper.class

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Runtime.Serialization.Json; 6 using System.IO; 7 using System.Text; 8 9 /// JSON序列化和反序列化辅助类 10 /// </summary> 11 public class JsonHelper 12 {

Newtonsoft.Json JsonHelper

1 using System; 2 using System.Linq; 3 using Newtonsoft.Json; 4 using Newtonsoft.Json.Serialization; 5 using System.Collections.Generic; 6 7 namespace TT.Utilities.Json 8 { 9 public static class JsonHelper 10 { 11 /// <summary> 12 /// 只序列号需要的字段 13 /

C#序列化及反序列化Json对象通用类JsonHelper

当今的程序界Json大行其道.因为Json对象具有简短高效等优势,广受广大C#码农喜爱.这里发一个序列化及反序列化Json对象通用类库,希望对大家有用. public class JsonHelper { #region 对象类型序列化为json 字符 /// <summary> /// 对象类型序列化为json 字符 /// </summary> /// <typeparam name="T">实体类型</typeparam> ///