我正在尝试重新创建这个json:
{
"auth": {
"identity": {
"methods": [
"password"
],
"password": {
"user": {
"id": "90551bd1bcf6474dba09c96617a33638",
"password": "hoeIX1.i-.M]wiu9"
}
}
},
"scope": {
"project": {
"id": "2440e4fa1725452cb2e14506cb5d63ec"
}
}
}
}
现在我正在做这个:
JObject auth = new JObject(
new JProperty("auth", new JObject(
new JProperty("identity", new JObject(
new JProperty("method",JArray.Parse("["password"]")),
new JProperty("password", new JObject(
new JProperty("user", new JObject(
new JProperty("id", JValue.CreateString(identityWithProject.Username)),
new JProperty("password", JValue.CreateString(identityWithProject.ProjectName))))))),
new JProperty("scope", new JObject(
new JProperty("project", new JObject(
new JProperty("id", JValue.CreateString(identityWithProject.ProjectName))))))))));
我得到这个错误:
"无法将Newtonsoft.Json.Linq.JProperty添加到Newtonsoft.Json.Linq.JArray。"
不工作的线路是:
new JProperty("method",JArray.Parse("["password"]"))
如果我删除了JArray部分,它工作得很好,我如何修复它,使它与数组部分一起工作?我发现的大多数例子都是JObjects数组,但事实并非如此。谢谢
看起来有一个放错地方的)
,这很有效:
var auth = new JObject(
new JProperty("auth", new JObject(
new JProperty("identity", new JObject(
new JProperty("methods", JArray.Parse("["password"]")),
new JProperty("password", new JObject(
new JProperty("user", new JObject(
new JProperty("id", JValue.CreateString(identityWithProject.Username)),
new JProperty("password", JValue.CreateString(identityWithProject.ProjectName)))))))), // 8 x ')'
new JProperty("scope", new JObject(
new JProperty("project", new JObject(
new JProperty("id", JValue.CreateString(identityWithProject.ProjectName))))))))); // 9 x ')'
我刚从最后一行移了一个)
到最后一行的第三行。
此外,如果属性"method"
要处理您的样本,则应将其命名为"methods"
。此外,在创建JProperties
时确实没有理由使用JValue.CreateString
,正如@Steven Brickner所指出的,您可以将JArray.Parse("["password"]")
简化为new JArray("password")
。
它可能更详细,但为了可读性,这里它是完全缩进的:
var auth =
new JObject(
new JProperty("auth",
new JObject(
new JProperty("identity",
new JObject(
new JProperty("methods", new JArray("password")),
new JProperty("password",
new JObject(
new JProperty("user",
new JObject(
new JProperty("id", identityWithProject.Username),
new JProperty("password", identityWithProject.ProjectName)
)
)
)
)
)
),
new JProperty("scope",
new JObject(
new JProperty("project",
new JObject(
new JProperty("id", identityWithProject.ProjectName)
)
)
)
)
)
)
);