Newtonsoft.json: JsonConvert.DeserializeObject๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•<t>() json ํ˜•์‹์ด ์ผ์น˜ํ•˜์ง€ ์•Š์œผ๋ฉด null์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๊นŒ?</t>

์— ๋งŒ๋“  2019๋…„ 11์›” 27์ผ  ยท  3์ฝ”๋ฉ˜ํŠธ  ยท  ์ถœ์ฒ˜: JamesNK/Newtonsoft.Json

JsonConvert.DeserializeObject๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•() json ํ˜•์‹์ด ์ผ์น˜ํ•˜์ง€ ์•Š์œผ๋ฉด null์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๊นŒ?

๊ฐ€์žฅ ์œ ์šฉํ•œ ๋Œ“๊ธ€

JSON ๊ฐ’์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ [Required] ์†์„ฑ์„ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋ชจ๋“  3 ๋Œ“๊ธ€

์˜ˆ๋ฅผ ๋“ค์–ด '๋ถˆ์ผ์น˜'๋ฅผ ์ •์˜ํ•ฉ๋‹ˆ๊นŒ? ์ผ๋ฐ˜์ ์œผ๋กœ ํ˜•์‹์ด ์ž˜๋ชป๋œ json(๋˜๋Š” ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ ์ œ์•ฝ ์กฐ๊ฑด์„ ์ „๋‹ฌํ•˜์ง€ ์•Š๋Š” json)์€ ์ด ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์— ๋Œ€ํ•œ ์˜ˆ์™ธ๋ฅผ ํŠธ๋ฆฌ๊ฑฐํ•ฉ๋‹ˆ๋‹ค. ๋‹น์‹ ์€ ๊ทธ๊ฒƒ๋“ค์„ ์žก์„ ์ˆ˜ ์žˆ์ง€๋งŒ ๊ทธ๊ฒƒ์€ ์˜์‹ฌ์Šค๋Ÿฌ์šด ์ผ์ž…๋‹ˆ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด:

ConditionSetting settingObj = new ConditionSetting();
string settingJson = JsonConvert.SerializeObject(settingObj);
// trying to parse a 'ObjectLayout' object from a 'ConditionSetting' json.
// here i expect to got a null return value or an exception, 
// but infact i got a non-null 'ObjectLayout' object
ObjectLayout layoutObj = JsonConvert.DeserializeObject<ObjectLayout>(settingJson);
print(layoutObj == null); // console print False

ํด๋ž˜์Šค ์ •์˜:

// ObjectLayout.cs
[System.Serializable]
public class ObjectLayout
{
    public bool IsSettled;
    public string Name;
    public Position Position;
    public Rotation Rotation;
}

// ConditionSetting.cs
[System.Serializable]
public class ConditionSetting
{
    public string PlanName;
    public Env Env;
    public Target Target;
    public Tank Tank;
    public int TankCount;
    public Shell Shell;
    public Fuze Fuze;
}
/////////////////////////////////////////////////////////////////////////////////

JSON ๊ฐ’์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ [Required] ์†์„ฑ์„ ์ž…๋ ฅํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ด ํŽ˜์ด์ง€๊ฐ€ ๋„์›€์ด ๋˜์—ˆ๋‚˜์š”?
0 / 5 - 0 ๋“ฑ๊ธ‰