我从类输入生成JSON字符串。我不知道为什么,但......它生成不同的输出(不同的项目),但具有相同的输入(从Web服务参考生成的类)。即:
第一个项目产生:
"{\"authToken\":{\"Token\":\"4f49f29e951d8d4f7e5b1f26aaf924771c9ed5fdfe6a23021d6720f2f5deead7==\",\"UserInfo\":{\"Email\":\"YS00982@mail.com\",\"Locked\":false,\"Phone\":null,\"UserLogin\":\"YS00982\",\"UserName\":\"YS00982 \"}},\"interactionModel\":{\"Description\":\"description\",\"Solicitor\":\"ry13578\",\"Title\":\"title\",\"Urgency\":\"3\"}}"
第二个项目生成:
"{\r\n \"authToken\": {\r\n \"token\": \"4f49f29e951d8d4f7e5b1f26aaf924771c9ed5fdfe6a23021d6720f2f5deead7==\",\r\n \"userInfo\": {\r\n \"email\": \"YS00982@mail.com\",\r\n \"locked\": false,\r\n \"userLogin\": \"YS00982\",\r\n \"userName\": \"YS00982 \"\r\n }\r\n },\r\n \"interactionModel\": {\r\n \"description\": \"description\",\r\n \"solicitor\": \"ry13578\",\r\n \"title\": \"title\",\r\n \"urgency\": \"3\"\r\n }\r\n}"
有两个主要区别:第一个字符(令牌与令牌)的大写字母以及" \ r \ n"添加到我的json。
AFAIK我没有在Newtonsoft中配置任何东西,所以我不知道为什么它在每个项目中以不同的方式运行。有谁知道原因?
示例代码:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://ws.domain.com/BackEndService/");
StringContent c = new StringContent($"{{ \"userLogin\": \"YS00982\", \"password\": \"pass\"}}", Encoding.UTF8, "application/json");
HttpResponseMessage r = await client.PostAsync("service.svc/Authenticate", c);
string d = await r.Content.ReadAsStringAsync();
string token = string.Empty;
D authres = JsonConvert.DeserializeObject<D>(d);
if (authres.d.success)
{
AuthToken authToken = new AuthToken();
authToken = authres.d.Data;
var model = new InteractionModel
{
Description = "description",
Title = "title",
Solicitor = "ry13578",
Urgency = "3"
};
object obj = new
{
authToken = authToken,
interactionModel = model
};
string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None, ContractResolver = null });
Console.WriteLine(json);
StringContent cc = new StringContent(json, Encoding.UTF8, "application/json");
r = await client.PostAsync("CAUMobileService.svc/CreateInteraction", cc);
d = await r.Content.ReadAsStringAsync();
Console.WriteLine(d);
}
祝你好运
答案 0 :(得分:2)
您似乎使用了两个单独的JsonSerializerSettings实例。默认设置配置为通过ContractResolver使用驼峰套管:
JsonConvert.DefaultSettings = () => new JsonSerializerSettings()
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Formatting = Formatting.Indented,
NullValueHandling = NullValueHandling.Ignore,
};
第二个实例未指定ContractResolver:
string json = JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.None, ContractResolver = null });
ContractResolver是控制套管的地方。 Formatting = Formatting.None将消除JSON中的换行符。