【发布时间】:2018-07-29 06:28:42
【问题描述】:
我从一些 API 收到了这种格式的 JSON 字符串。
{
"onlineRequest":{
"MobileNumber":"75484568",
"ProductNo":"100",
"JsonFile":{
"dropdown":[
{
"@para-id":"2572",
"@new-code":"",
"@text":"This is first dropdown",
"option":[
{
"@text":"Option 1",
"@value":"0"
}
]
},
{
"@para-id":"2584",
"@new-code":"",
"@text":"This is second dropdown",
"option":[
{
"@text":"Excellent",
"@value":"2"
}
]
},
{
"@para-id":"2575",
"@new-code":"",
"@text":"This is third dropdown",
"option":[
{
"@text":"Not Available",
"@value":"1"
}
]
}
]
}
}
}
为了这个 JSON 字符串,我需要将值绑定到
JSON。每个参数 ID 都有单独的 @value。这是动态的。 @value 的值可以是 0,1,2,3,4
当@para-id = 2572 时,
如果@value = 0,我需要将值传递给@new-code = 50,
如果@value = 1,我需要将值传递给@new-code = 60,
如果@value = 2,我需要将值传递给@new-code = 70
当@para-id = 2584 时,
如果@value = 0,我需要将值传递给@new-code = 10,
如果@value = 1,我需要将值传递给@new-code = 20,
如果@value = 2,我需要将值传递给@new-code = 30,
当@para-id = 2575 时,
如果@value = 0,我需要将值传递给@new-code = "A",
如果@value = 1,我需要将值传递给@new-code = "B"
预期输出:
"dropdown":[
{
"@para-id":"2572",
"@new-code":"50",
"@text":"This is first dropdown",
"option":[
{
"@text":"Option 1",
"@value":"0"
}
]
},
{
"@para-id":"2584",
"@new-code":"30",
"@text":"This is second dropdown",
"option":[
{
"@text":"Excellent",
"@value":"2"
}
]
},
{
"@para-id":"2575",
"@new-code":"B",
"@text":"This is third dropdown",
"option":[
{
"@text":"Not Available",
"@value":"1"
}
]
}
]
如何使用 C# 来做到这一点。请帮我解决这个问题。
更新:
为了JSON,我创建了一个模型类。但问题是使用@text、@value 和@para-id 时。我知道我不能创建这样的字段
public class Option
{
public string @text { get; set; }
public string @value { get; set; }
}
public class Dropdown
{
public string @para-id { get; set; }
public string @new-code { get; set; }
public string @text { get; set; }
public List<Option> option { get; set; }
}
public class JsonFile
{
public List<Dropdown> dropdown { get; set; }
}
public class OnlineRequest
{
public string MobileNumber { get; set; }
public string ProductNo { get; set; }
public JsonFile JsonFile { get; set; }
}
public class RootObject
{
public OnlineRequest onlineRequest { get; set; }
}
【问题讨论】:
-
根据您的 api json 创建模型并将 json 对象转换为您的模型类型,然后您可以在下拉列表中进行 foreach 并有条件地设置新代码
-
@HiteshKansagara 你能帮我这样做吗,我不知道这样做。请先生
-
@HiteshKansagara 我添加了一个模型类。这是正确的吗?
标签: c# json dictionary parameters json.net