【发布时间】:2017-03-27 12:07:33
【问题描述】:
我发现最好的解决方案是堆栈中的可用解决方案没有针对嵌套 json 对象的答案,它们仅处理 liner json 值。但是我有数据要发送就像
{ ob: { a: "78", b: { a: "gffg", h: {m:67, j:"fff"} } } }
如果我想在 php 中这样做,我会这样做
$json = $_POST['ob'];
$obj = json_decode($json);
但在 c# 中我不能这样做。因此,如果有任何可用的内置方法,我将不胜感激,并且我很乐意帮助我修复我的以下代码
我想制作一个嵌套字典(不过我更喜欢 JOBject)。为了便于显示输出,我对结果进行了序列化,
我从以下代码中取得的结果是
{"a":"78","ob":{},"ob.b":{"a":"gffg"},"ob.b.h":{"m":"67","j":"fff"}} 但想要的结果就像发送的数据 { "ob": { "a": "78", "b": { "a": "gffg", "h": {m:67, "j":"fff"} } } } 代码是
string getJsonStringFromQueryString()
{
Dictionary<string, object> dic = new Dictionary<string, object>();
var nvc = Request.QueryString;
foreach (string key in nvc.Keys)
{
string[] values = nvc.GetValues(key);
string tempKey = key;
tempKey = tempKey.Replace("[", ".").Replace("]", "");
if (values.Length == 1)
dic.Add(tempKey, values[0]);
else
dic.Add(tempKey, values);
}
//It is giving me
{[ob.a, 78]}
{[ob.b.a, gffg]}
{[ob.b.h.m, 67]}
{[ob.b.h.j, fff]}
var result = makeNestedObject(dic);
var json = new JavaScriptSerializer().Serialize(result);
return json;
}
我正在尝试按原样添加叶键及其值,并将所有其他键添加为字典
Dictionary<string, object> makeNestedObject(Dictionary<string, object> qsDictionar)
{
Dictionary<string, object> result = new Dictionary<string, object>();
foreach (string key in qsDictionar.Keys)
{
string temp = "";
if (key.Contains("."))
{
string[] ar = key.Split('.');
if (ar.Length > 2)
{
for (int i = 0; i < ar.Length - 1; i++)
{
temp = ar[0];
for (int j = 1; j <= i; j++)
{
temp += "." + ar[j];
}
//above is getting the previous key i want to use as dictionary, leaving the leaf key.
try
{
Dictionary<string, object> forTry = (Dictionary<string, object>)result[temp];
}
catch
{
result.Add(temp, new Dictionary<string, object>());
}
}
((Dictionary<string, object>)result[temp]).Add(ar[ar.Length - 1], qsDictionar[key]);
}
else
result.Add(ar[1], qsDictionar[key]);
}
}
return result;
}
【问题讨论】:
-
我自己正在使用来自
using Newtonsoft.Json.Linq;的JObject将字符串转换为JSON 对象。通过JObject.Parse(json),您可以通过在JObject上使用['key_name']来访问密钥 -
是的,亲爱的,我们可以。但问题在于查询字符串中的 makinh JObject
标签: c# json dictionary query-string