如何使用SuperObject序列化包含点(例如IP地址)的JSON密钥? [英] How to serialize JSON key containing dots (like e.g. IP address) with SuperObject?

查看:187
本文介绍了如何使用SuperObject序列化包含点(例如IP地址)的JSON密钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试保存IP是关键的JSON.预期的JSON结果是:

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

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

Delphi SuperObject代码:

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将点解析为JSON对象的路径定界符:

SuperObject parses dots as path delimiters of a JSON object:

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

如何使用SuperObject正确将IP保存为JSON密钥?

推荐答案

解决方案是从字符串创建JSON对象

The solution is to create JSON object from string

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

另一种添加方式(不要与.O []一起使用,因为AsObject为不存在的键给出nil):

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"}}

这篇关于如何使用SuperObject序列化包含点(例如IP地址)的JSON密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆