我向外部API发出请求并获取JSON数据,返回的数据格式如下:
abnCallback({
"Abn": "53660112345",
"AbnStatus": "Active",
"AbnStatusEffectiveFrom": "2022-06-16",
"Acn": "660198745",
"AddressDate": "2022-06-16",
"AddressPostcode": "3000",
"AddressState": "VIC",
"BusinessName": [],
"EntityName": "Company name pty ltd",
"EntityTypeCode": "PRV",
"EntityTypeName": "Private Company",
"Gst": "2022-06-16",
"Message": ""
})
我正试图通过以下操作将其映射到一个模型:
var jsonString = await response.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<ABRPayloadSearchResults>(jsonString);
我的模型是这样的:
public class ABRPayloadSearchResults
{
public string Abn { get; set; }
public string AbnStatus { get; set; }
public string AbnStatusEffectiveFrom { get; set; }
public string Acn { get; set; }
public string AddressDate { get; set; }
public string AddressPostcode { get; set; }
public string AddressState { get; set; }
public object[] BusinessName { get; set; }
public string EntityName { get; set; }
public string EntityTypeCode { get; set; }
public string EntityTypeName { get; set; }
public string Gst { get; set; }
public string Message { get; set; }
}
我的问题是,返回的JSON
在开始时有abnCallBack(
,这阻止了json正确映射到我的类,以前有人处理过这种情况吗?
此格式称为JSONP
。它将JSON对象封装在(javascript(函数调用中,使浏览器能够通过<script>
下载JSON。这可以用来绕过跨源策略,从其他域加载JSON。
我不相信有一种内置的方法可以在C#中反序列化JSONP,但您应该能够很容易地操作字符串来删除函数名和括号。请参阅例如如何反序列化JSONP响应(最好使用JsonTextReader,而不是字符串(?
获取左大括号的索引和右大括号的字符数。将这些参数输入到子字符串操作中。这将返回方括号和方括号之间的内容。您需要添加对真实情况的处理,例如额外的花括号和空字符串,但代码示例给出了大致的想法。
var input = @"abnCallback({
""Abn"": ""53660112345"",
""AbnStatus"": ""Active"",
""AbnStatusEffectiveFrom"": ""2022-06-16"",
""Acn"": ""660198745"",
""AddressDate"": ""2022-06-16"",
""AddressPostcode"": ""3000"",
""AddressState"": ""VIC"",
""BusinessName"": [],
""EntityName"": ""Company name pty ltd,
""EntityTypeCode"": ""PRV"",
""EntityTypeName"": ""Private Company"",
""Gst"": ""2022-06-16"",
""Message"": """"})";
int from = input.IndexOf("{");
int to = input.IndexOf("}");
var jsonString = input.Substring(from, to - from + 1);