C#Json格式化响应

时间:2017-08-18 09:47:51

标签: c# json json.net

我知道我需要格式化的Newtonsoft Json响应,但我不知道该怎么做,我似乎无法找到可以帮助我的教程或任何类型的文档。

这是我现在的代码。 dtb是我需要在格式化的Newtonsoft Json响应

中返回的数据库响应
da.Fill(dtb)
return Json(dtb);

这不起作用,当我尝试运行下一批代码时出现错误

Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>((Newtonsoft.Json.Linq.JObject.Parse(response)["d"]).ToString());
UserModel m = (UserModel)JsonConvert.DeserializeObject<UserModel>(response);
if (m.Username == context.UserName && m.PasswordHash == myHash)
{

我不确定为什么它会在这个说法错误的第一行打破

+       $exception  {"Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."}   Newtonsoft.Json.JsonReaderException

错误编辑1:

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'AuthorizationServer.api.Models.UserModel' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.

我的代码现在看起来像这样

dynamic res = JsonConvert.DeserializeObject<Dictionary<string, string>>((Newtonsoft.Json.Linq.JToken.Parse(response)[0]).ToString());
        UserModel m = (UserModel)JsonConvert.DeserializeObject<UserModel>(res);
        if (m.Username == context.UserName && m.PasswordHash == myHash)

但它在UserModel m = (UserModel)JsonConvert.DeserializeObject<UserModel>(res);

时给了我一个错误
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException occurred
HResult=0x80131500
Message=The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<AuthorizationServer.api.Models.UserModel>(string)' has some invalid arguments
Source=AuthorizationServer.api
StackTrace:
at AuthorizationServer.api.Providers.CustomOAuthProvider.GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) in C:\Users\wilsona\Documents\Visual Studio 2017\Projects\JsonWebTokensWebApi\AuthorizationServer.api\Providers\CustomOAuthProvider.cs:line 66
at Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerHandler.<InvokeTokenEndpointResourceOwnerPasswordCredentialsGrantAsync>d__3f.MoveNext()

用户模型类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AuthorizationServer.api.Models
{
public class UserModel
{

    public string Username { get; set; }
    public string PasswordHash { get; set; }
    public int UserID { get; set; }
    public string Roles { get; set; }

    public UserModel(string Username, string PasswordHash, int UserID, string Roles)
    {
        this.Username = Username;
        this.PasswordHash = PasswordHash;
        this.UserID = UserID;
        this.Roles = Roles;
    }

}
}

json return

[{"UserID":1,"Username":"andy","PasswordHash":"$2a$10$8PJOsziVcElM6pi9pF8DiuSoE8JS14co6XBjGMITwoZOAPhCmOhK","Roles":"admin"}]

然后通过dynamic res = JsonConvert.DeserializeObject<Dictionary<string, string>>((Newtonsoft.Json.Linq.JToken.Parse(response)[0]).ToString());

传递

当它到达UserModel m = (UserModel)JsonConvert.DeserializeObject<UserModel>(res);

时,它会中断

出现此错误Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<AuthorizationServer.api.Models.UserModel>(string)' has some invalid arguments'

1 个答案:

答案 0 :(得分:3)

问题是Json是作为数组发送的。您必须将其反序列化为数组。

此代码适用于我。

var jToken = JToken.Parse(response);
var users = jToken.ToObject<List<UserModel>>(); //Converts the Json to a List<Usermodel>
var user = users[0];