본문 바로가기
Unity/문제 해결

[Unity/.Net/문제해결] Socket 통신 Netonsoft Json Array Parsing

by 왹져박사 2024. 9. 3.

 

프로젝트를 진행하며 서버 DB 데이터 구조에 큰 변동이 있어 Json 데이터를 새롭게 받아오게 되었다. 

 

이전의 데이터는 List 형태로 들어오는 일반적인 단순한 구조의 Json의 형태였다. 

그래서 단순하게 JsonConvert.DeserializeObject<형식>(download.text);의 형태로 바로 받아볼 수 있었다. 

 

하지만, 이번에 들어오는 데이터를 확인해보니, 처음 보는 형태라 당황스러웠다. 

어쨌든 해결해야 하니, 에러를 기반으로 구글링 한 결과, Json의 구조에 대하여 자세히 공부하게 되었다. 

 

받은 데이터는 {"result":1, "data":[{\"idx\":1, ....\"data\"[{\\\"name\\\":\\\"str\\\"...}]"} 이런 형태로 출력되었다. 

 

 

구글링한 결과, [ ] 이 대괄호가 있다는 것은 JArray 형식을 뜻한다. JObject들의 배열 구조. 

 

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JArray.htm

 

JArray Class

Represents a JSON array. Namespace:  Newtonsoft.Json.Linq Assembly:  Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 12.0.1+509643a8952ce731e0207710c429ad6e67dc43db public class JArray : JContainer, IList , ICollection , IEnumerable , IEnumerable The J

www.newtonsoft.com

 

 

JArray를 구성하는 JObject,  (Key와 Value로 구성되는 Dictionary 같은 느낌?실제로 IDictionary 인터페이스를 상속받음)

 

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

 

JObject Class

Represents a JSON object. Namespace:  Newtonsoft.Json.Linq Assembly:  Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 12.0.1+509643a8952ce731e0207710c429ad6e67dc43db public class JObject : JContainer, IDictionary , ICollection >, IEnumerable >, IEnumer

www.newtonsoft.com

 

 

이를 구성하는 JProperty..? property가 속성이니 속성이라는 속성??이 있다는 것이 잘 이해가 안 가지만 다른 예제들을 보니 JToken과 JObject를 원활히 변환시키기 위한 형식이 아닐까.. 추측해 본다. 

 

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JProperty.htm

 

JProperty Class

Represents a JSON property. Namespace:  Newtonsoft.Json.Linq Assembly:  Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 12.0.1+509643a8952ce731e0207710c429ad6e67dc43db public class JProperty : JContainer The JProperty type exposes the following members

www.newtonsoft.com

 

마지막으로 JToken! JObject의 Value인 JToken을 받아올 수 있다. 

 

https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JToken.htm

 

JToken Class

Represents an abstract JSON token. Namespace:  Newtonsoft.Json.Linq Assembly:  Newtonsoft.Json (in Newtonsoft.Json.dll) Version: 12.0.1+509643a8952ce731e0207710c429ad6e67dc43db public abstract class JToken : IJEnumerable , IEnumerable , IEnumerable, IJso

www.newtonsoft.com

 

 

결국 내가 찾던 JArray는 JObject와 JToken을 활용하여 파싱하는 작업을 해야 했다. 

처음에는 어떤 블로그를 보고 무작정 따라했다. 위의 JProperty로 중간 변환을 했던 것 같은데, 

진행하던 프로젝트에는 아무런 반응이 없었다. 에러도 안 나서 무서웠다...

 

이 방법은 아닌 듯 하여 위에 Netonsoft 공식 홈페이지를 보며 구성을 확실하게 파악하고 사용하자 싶어 직접 공부하였다. 

그렇게 적용하게 된 결과이다. 

 

namespace newtonsoft.json.linq를 사용해야 한다. 

//예시!

		if (req.result == UnityWebRequest.Result.Success)
		{
			//인증 성공

			//리스트 json 역직렬화
			response res = new response();
			res.list = new List<Info>();

			//json parsing test
			JObject jsonObject = JObject.Parse(req.downloadHandler.text);
			Debug.Log(jsonObject);
			JToken token0 = jsonObject["data"];
			Debug.Log(token0);
			JArray jObjects0 = JArray.Parse(token0.ToString());
			foreach(var token1 in jObjects0)
            {
				Debug.Log(token1);
				Debug.Log(token1["data"]);

				JArray jObjects1 = JArray.Parse(token1["data"].ToString());

				foreach(var token2 in jObjects1)
                {
					Debug.Log(token2);
					res.list.Add(JsonConvert.DeserializeObject<Info>(token2.ToString()));
                }
			}

 

 

마지막은 바로 변환하는 다른 방법이 있을 수도 있을 듯 하지만 원래 방식의 역직렬화로 마무리하였다. 

 

오늘도 새롭게 배우게 되어 너무 재밌는 하루였다!!!!😊😊