【发布时间】:2022-01-24 04:52:58
【问题描述】:
我有几个不同的 JSON 对象。
拳头 JSON 对象
{
"api": {
"NAME":"CUSTOMER_CREATE",
"QUERY":"CUSTOMER_CREATE"
},
"header" : {
"PartyNumber": "1488002",
"OrganizationName": "Test Organization-02",
"RawPhoneNumber": "9199199199",
"PartyUsageCode": "EXTERNAL_LEGAL_ENTITY",
"Address": [
{
"AddressType": "BILL_TO",
"Address1": "77 College Rd",
"Address2": "London NW10 5SE",
"Address3": "London NW10 5SF",
"Address4": "London NW10 5SG",
"City": "London",
"Country": "GB",
"PostalCode": "NW10 5ES"
}
第二个 JSON 对象
"api": {
"NAME":"ITEM_CREATE",
"QUERY":"ITEM_CREATE"
},
"header" :
{
"OrganizationCode": "IM_MASTER_ORG",
"ItemClass" : "Root Item Class",
"ItemNumber" : "TEST-01",
"ItemDescription" : "TEST-01",
"ItemStatusValue" : "Active",
"PrimaryUOMValue" : "Each",
"LifecyclePhaseValue" : "Production"
}
我也有很多这样的 JSON 对象。所有 JSON 对象都不相同。所以我想编写一个 C# 类来将这个任何 JSON 对象转换为 C# 对象。那么你能请我一堂课来转换这些 JSON 对象吗?
目前我正在使用这个类来转换 Json 对象。但我想把它做成一个动态类
public class MHScaleMessage {
//public string api { get; set;}
public Dictionary<string, string> api { get; set;} = new Dictionary<string, string>();
public Dictionary<string, string> header {get; set; } = new Dictionary<string, string>();
public List<Dictionary<string, string>> lineItems { get; set; } = new List<Dictionary<string, string>>();
public static string GetValue(Dictionary<string, string> d, string key, string defaultVal="") {
if (key == null) return defaultVal;
return d.TryGetValue(key, out string val) ? val : defaultVal;
}
public static int GetValueAsInt(Dictionary<string, string> d, string key, int defaultVal=0) {
if (key == null) return defaultVal;
string val = d.TryGetValue(key, out val) ? val : null;
if (val == null) return defaultVal;
return int.TryParse(val, out _) ? 0 : defaultVal;
}
public string ToJsonString() {
var options = new JsonSerializerOptions
{
WriteIndented = true,
IgnoreNullValues = true
};
return System.Text.Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(this, options));
}
public string _ToString() {
string s="";
s += "{"; s += "\n";
s += "api = " + api; s += ","; s += "\n";
s += "header ="; s += "\n";
s += "{";
header.ToList().ForEach(x => s += x.Key + " = " + x.Value + "\n");
s += "}"; s += ","; s += "\n";
s += "lineItems"; s += "\n";
s += "{"; s += "[";
lineItems.ForEach(x => {
x.ToList().ForEach(y => {
s += y.Key + " = " + y.Value;
s += ","; s += "\n";
}
);
});
s += "]"; s += "}"; s += "\n";
s += "}";
return s;
}
}
之后我使用以下方法来执行 API。这个方法我可以传参数。
private static MHScaleMessage PerformAPIFunction(MHScaleMessage requestObj)
{}
【问题讨论】:
-
你可能想看看newtonsoft.com/json。根据经验,您应该通过一个小代码示例提出问题,以便人们可以帮助您找出缺少的内容。
标签: c# json asp.net-core