2

I have a case when I get a very big text data & each line contains some metadata + json data string. I need to process the json data on each line.

This is what I have:

public Data GetData(string textLine)
{
    var spanOfLine = textLine.AsSpan();
    var indexOfComma = spanOfLine.IndexOf(":");
    var dataJsonStringAsSpan = spanOfLine.Slice(indexOfComma + 1);

    // now use dataJsonStringAsSpan which is ReadOnlySpan<char> to deserialize the Data
}

Where Data is a Dto class which has bunch of (7) different attributes:

public class Data
{
    public int Attribute1 { get; set; }

    public double Attribute2 { get; set; }
    // ... more properties, emitted for the sake of brevity
}

I'm trying to achieve this with System.Text.Json API. Surprisingly it doesn't have any overload to deserialize from ReadOnlySpan<char>, so I come up with this:

public Data GetData(string textLine)
{
    var spanOfLine = textLine.AsSpan();
    var indexOfComma = spanOfLine.IndexOf(":");
    var dataJsonStringAsSpan = spanOfLine.Slice(indexOfComma + 1);

    var byteCount = Encoding.UTF8.GetByteCount(dataJsonStringAsSpan);
    Span<byte> buffer = stackalloc byte[byteCount];
    Encoding.UTF8.GetBytes(dataJsonStringAsSpan, buffer);
    var data = JsonSerializer.Deserialize<Data>(buffer);
    return data;
}

While this works, it looks very convoluted.

Is this the way to go or am I missing something more simple ?

4

1 回答 1

-1

这会一样吗?只是阅读你的代码,它看起来会做同样的事情......

public Data GetData(string textLine)
{
    var split = textLine.Split(new char[] {':'});
    var data = JsonSerializer.DeserializeObject<Data>(split[1]);
    return data;
}
于 2019-11-13T21:43:35.313 回答