How to serialize JSON key containing dots (like e.g. IP address) with SuperObject?

你。 提交于 2019-12-08 19:47:42

问题


I'm trying to save JSON where IP is a key. Expected JSON result is:

{"SnmpManagers":[{"10.112.25.235":162}]}

The Delphi SuperObject code:

const
  IpAddr = '10.112.25.235';
  Port = 162;
var
  tmp: TSuperObject;
begin
  tmp := TSuperObject.Create;
  tmp.I[IpAddr] := Port;
  Json.A['SnmpManagers'].Add(tmp);
end;

SuperObject parses dots as path delimiters of a JSON object:

{"SnmpManagers":[{"10":{"112":{"25":{"235":162}}}}]}

How to save IP as a JSON key correctly with SuperObject ?


回答1:


The solution is to create JSON object from string

Json.A['SnmpManagers'].Add(SO(Format('{"%s":%d}', [IpAddr, Port])));

Another way to add (do not use with .O[] because AsObject gives nil for non existing keys):

// for a simple key-value object
Json.AsObject.S['1.2.3'] := 'a'; // gives us {{"1.2.3":"a"}}
Json.AsObject.S['4.5'] := 'b'; // gives us {{"1.2.3":"a"}, {"4.5":"b"}}



回答2:


This also works:

var    
  tmp: ISuperObject;
begin
  tmp := SO([IpAddr, port]);
  Json.A['SnmpManagers'].Add(tmp);


来源:https://stackoverflow.com/questions/22652878/how-to-serialize-json-key-containing-dots-like-e-g-ip-address-with-superobjec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!