Custom JSON Derivative Format

后端 未结 1 1087
南笙
南笙 2021-01-20 15:30

I would like to have a serialization format that is nearly identical to JSON, except that key-values are represented as =\"\" instead of

相关标签:
1条回答
  • 2021-01-20 16:00

    Rather than creating your own converter, you're going to need to create your own subclass of JsonWriter that writes to your custom file format. (This is how Json.NET implements its BsonWriter.) In your case, your file format is close enough to JSON that you can inherit from JsonTextWriter:

    public class TsonTextWriter : JsonTextWriter
    {
        TextWriter _writer;
    
        public TsonTextWriter(TextWriter textWriter)
            : base(textWriter)
        {
            if (textWriter == null)
                throw new ArgumentNullException("textWriter"); 
            QuoteName = false;
            _writer = textWriter;
        }
    
        public override void WriteStartObject()
        {
            SetWriteState(JsonToken.StartObject, null);
    
            _writer.Write('[');
        }
    
        protected override void WriteEnd(JsonToken token)
        {
            switch (token)
            {
                case JsonToken.EndObject:
                    _writer.Write(']');
                    break;
                default:
                    base.WriteEnd(token);
                    break;
            }
        }
    
        public override void WritePropertyName(string name)
        {
            WritePropertyName(name, true);
        }
    
        public override void WritePropertyName(string name, bool escape)
        {
            SetWriteState(JsonToken.PropertyName, name);
    
            var escaped = name;
            if (escape)
            {
                escaped = JsonConvert.ToString(name, '"', StringEscapeHandling);
                escaped = escaped.Substring(1, escaped.Length - 2);
            }
    
            // Maybe also escape the space character if it appears in a name?
            _writer.Write(escaped.Replace("=", @"\u003d"));// Replace "=" with unicode escape sequence.
    
            _writer.Write('=');
        }
    
        /// <summary>
        /// Writes the JSON value delimiter.  (Remove this override if you want to retain the comma separator.)
        /// </summary>
        protected override void WriteValueDelimiter()
        {
            _writer.Write(' ');
        }
    
        /// <summary>
        /// Writes an indent space.
        /// </summary>
        protected override void WriteIndentSpace()
        {
            // Do nothing.
        }
    }
    

    Having done this, now all classes will be serialized to your custom format when you use this writer, for instance:

            var tracey = new TraceyData();
            tracey.TraceID = Guid.NewGuid().ToString();
            tracey.SessionID = "5";
            tracey.Tags["Referrer"] = "http://www.sky.net/deals";
            tracey.Stuff = new string[] { "Alpha", "Bravo", "Charlie" };
            tracey.Application = "Responsive";
    
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore; 
    
            using (var sw = new StringWriter())
            {
                using (var jsonWriter = new TsonTextWriter(sw))
                {
                    JsonSerializer.CreateDefault(settings).Serialize(jsonWriter, tracey);
                }
                Debug.WriteLine(sw.ToString());
            }
    

    Produces the output

    [Application="Responsive" SessionID="5" TraceID="2437fe67-9788-47ba-91ce-2e5b670c2a34" Tags=[Referrer="http://www.sky.net/deals"] Stuff=["Alpha" "Bravo" "Charlie"]]
    

    As far as deciding whether to serialize properties based on the presence of a [Safe] attribute, that's sort of a second question. You will need to create your own ContractResolver and override CreateProperty, for instance as shown here: Using JSON.net, how do I prevent serializing properties of a derived class, when used in a base class context?

    Update

    If you want to retain the comma separator for arrays but not objects, modify WriteValueDelimiter as follows:

        /// <summary>
        /// Writes the JSON value delimiter.  (Remove this override if you want to retain the comma separator.)
        /// </summary>
        protected override void WriteValueDelimiter()
        {
            if (WriteState == WriteState.Array)
                _writer.Write(',');
            else
                _writer.Write(' ');
        }
    
    0 讨论(0)
提交回复
热议问题