Json 파싱 관련 질문드립니다.

Newton 을 이용하면 좋겠지만 사용하지 못할 사정이 있어서요. ㅠㅠ

서버에서
{“SendData”: [ {“CTRLR_EQUIP_NO”: “1”, “CTRLR_NM”: “김용”}, {}… ] }

이런형식으로 되 있습니다. 위 Json string 에서 [] 배열부분을 추출하여
루프를 돌려서 데이타를 받고 싶은데

sendData 는 Console.WriteLine(sendData) 찍어본 결과 :
System.Collections.Generic.List`1[System.Object]
이렇게 나옵니다.

그런데 JSON내장객체로 이렇게 실행하면 Exeption 오류가 잔뜩나옵니다. ㅠㅠ
var cardData = System.Text.Json.JsonSerializer.Deserialize<Card[]>(sendData);

아래는 코딩중에는 오류(킺줄)이 안나옵니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IgsCommon.IOC;
using IgsCommon.IOC.Attibutes;
using IgsCommon.Util.Helper;
using AppWatchService.Api.Model;
using IgsCommon.Handler.DB;
using IgsCommon.Logger;

using System.Text.Json;

namespace AppWatchService.Api.Service
{
    [Injection(ServiceName = "PROCESS.ADD_PROCESS", InterfaceType = typeof(IApiService), LifeCycle = LifeCycle.Singleton)]
    class ProcessAddService : BaseApiService
    {

IOCContainer.FindService<FaceFeatureContainer>("CONTAINER.FEATURE");
        //private ICommonLogger   _logger     = IGSLoggerFactory.LOGGER;
        private SmartSqlHandler _dbHandler  = IOCContainer.FindService<SmartSqlHandler>("DB.FR_SERVER");

        protected override ResponseApiVO InternalExecute(Dictionary<string, object> inboundParam)
        {
            ResponseApiVO retVO = new ResponseApiVO();

            // string domainId  = inboundParam["DOMAIN_ID"].Nvl();
            // string visitorId = inboundParam["VISITOR_ID"].Nvl();
            // string cardNo    = inboundParam["CARD_NO"].Nvl();
            string sendData        = inboundParam["SendData"].Nvl();



//string jsonString = "[{\"Id\":1,\"Address\":{\"Zip\":\"98052\",\"State\":\"WA\"}}]";
//string jsonString = "[{\"Id\":\"이\"}, {\"Id\":\"백\"}, {\"Id\":\"원\"}]";
string jsonString   = sendData;
JsonDocument jdom = JsonDocument.Parse(jsonString);
JsonElement jroot = jdom.RootElement;
for (int i = 0; i < jroot.GetArrayLength(); i++)
{
    JsonElement jaddr = jroot[i].GetProperty("CTRLR_EQUIP_NO");
    //string zip = jaddr.GetProperty("Zip").GetString();
    Console.WriteLine(jaddr.GetString());

}
Console.Read();

    

}


상황을 재현할 수 있는 샘플 코드와 Json string, 발생하는 Exception의 종류 정도는 첨부해 주셔야 글을 읽는 사람들이 확인이라도 해볼 수 있지 않을까요.

2개의 좋아요

무슨 문제가 있는 건지 질문을 좀 더 정리 해 주시고 예시 코드 등을 올려주시면 더 좋을 것 같습니다.

지금 상황에서 보자면 현재 "SendData"가 key, 말씀하신 [] 안에 있는 것이 value 인 것 같습니다.
또한 [] 안쪽에 있는 것도 string, string 형태의 dictionary 같고요

아래 쪽을 보면 이중 반복문으로 짜놓으신것 같은데
컴파일 타임중에 오류는 발생하지 않고 런 타임 중 오류가 발생한다면
아마도 Type 혹은 index쪽의 문제가 있어 보입니다.
type을 object, var 보단 명시적으로 하고 오류를 찾아가는게 더 좋을 것 같습니다.

테스트중인 소스입니다.

맨위의 JSON 이 테스트 JSON 인데요

중간에 JSON string으로 할 땐 오류없이 잘나오는데
웹서버에서 맨위 JSON 을 던지면 아래처럼 나옵니다. ㅠㅠ

15:37:20 ERR] === exception detail
System.Text.Json.JsonReaderException: ‘S’ is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan1 bytes) at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker) at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first) at System.Text.Json.Utf8JsonReader.ReadSingleSegment() at System.Text.Json.Utf8JsonReader.Read() at System.Text.Json.JsonDocument.Parse(ReadOnlySpan1 utf8JsonSpan, Utf8JsonReader reader, MetadataDb& database, StackRowStack& stack)
at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory1 utf8Json, JsonReaderOptions readerOptions, Byte[] extraRentedBytes) at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory1 json, JsonDocumentOptions options)
at System.Text.Json.JsonDocument.Parse(String json, JsonDocumentOptions options)
at AppWatchService.Api.Service.ProcessAddService.InternalExecute(Dictionary`2 inboundParam) in C:\DSMV\TEMP\VS\AppWatchService\Api\Service\ProcessAddService.cs:line 39
at AppWatchService.Api.Service.BaseApiService.<>c__DisplayClass1_0.<b__0>d.MoveNext() in C:\DSMV\TEMP\VS\AppWatchService\Api\Service\BaseApiService.cs:line 36