andy wilson
andy wilson

Reputation: 970

C# Json formatted response

I know I need a formatted Newtonsoft Json response but I don't know how to do it and I can't seem to find a tutorial or any sort of documentation that could help me out.

This is the code I have right now. dtb is the response from the database that I need to return in a formatted Newtonsoft Json response

da.Fill(dtb)
return Json(dtb);

This doesn't work and I'm getting an error when I try and run the next lot of code which is

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)
{

I'm not sure why it breaks at the first line of this saying error

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

error edit 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.

My code now looks like this

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)

But it gives me an error at that the UserModel m = (UserModel)JsonConvert.DeserializeObject<UserModel>(res); saying

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()

user model class

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"}]

Which then gets passed through dynamic res = JsonConvert.DeserializeObject<Dictionary<string, string>>((Newtonsoft.Json.Linq.JToken.Parse(response)[0]).ToString());

Which works then breaks when it hits UserModel m = (UserModel)JsonConvert.DeserializeObject<UserModel>(res);

with this error Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<AuthorizationServer.api.Models.UserModel>(string)' has some invalid arguments'

Upvotes: 1

Views: 2316

Answers (1)

Mueui
Mueui

Reputation: 181

The problem is that the Json is sent as array. You have to deserialize it to an Array.

This code works for me.

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

Upvotes: 5

Related Questions