Utf8JsonReader odczytywanie tablicy

0

Tak wyglada json

var json = @"{""ErrorType"":""BadRequestError"",""StatusCode"":400,""StackTrace"":"" STACKTRACEFOO "",""Messages"":[""User does not exist""]}";

Deserializuje jsona w ten sposob

            var serializeOptions = new JsonSerializerOptions();
            serializeOptions.Converters.Add(new ErrorConverter());
            serializeOptions.WriteIndented = true;
            var error = JsonSerializer.Deserialize<Error>(json, serializeOptions);

wszystko działa pieknie dopoki nie trafi na messages / tablice

kod ktory deserialuzuje liste jest ponizej.

        private List<string> PopulateList(in Utf8JsonReader reader)
        {
            var list = new List<string>();

            if (reader.TokenType != JsonTokenType.StartArray)
            {
                throw new JsonException("Failed to deserialize array.");
            }

            while (reader.Read())
            {
                if (reader.TokenType == JsonTokenType.EndArray)
                {
                    break;
                }
                

                var item = reader.GetString();
                if (!string.IsNullOrEmpty(item))
                {
                    list.Add(item);    
                } 

            }
            
            return list;
        }

dostaje Exceptiona nastepnujacego

System.InvalidOperationException: Cannot get the value of a token type 'StartArray' as a string.

na linijce

var item = reader.GetString();

z kolei reader.Read() "nic" nie robi. reader.TokenType jest zawsze JsonTokenType.StartArray,

Pytanie, co robie zle?

0

Jest to bardzo dziwne ,że to nie działa. Szczególnie ,że w internecie znajdują łudząco podobne przykłady np

public override HashSet<string> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
	if (reader.TokenType != JsonTokenType.StartArray)
		throw new JsonException("Expected StartArray token");

	var set = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

	while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
	{
		set.Add(reader.GetString());
	}

	return set;

}

Dla mnie jest to 1:1 to co ty masz. Może gdzieś w wywołaniu tej metody jest błąd? Ale trudno mi nawet wymyślić na czym miałby on polegać

0

zrobilem repo z projektem ktory daje error

https://github.com/fasadin/deserializerError

5

@fasadin: Do PopulateList przekazujesz Utf8JsonReader z modyfikatorem in.

Według dokumentacji:
Never pass a struct as an in parameter unless it's declared with the readonly modifier or the method calls only readonly members of the struct. Violating this guidance may negatively affect performance and could lead to an obscure behavior.

1 użytkowników online, w tym zalogowanych: 0, gości: 1