how to deserialize this JWT into a class with json.net - json.net

I have a JWT with the following content:
{
"jti":"b17373d5-2755-435b-916a-9b87c9354427",
"resource_access":"{"test-app":{"roles":["anonymous"]}}"
}
the issue is the resource_access part:
it it looks like:
dictionary<string, dictionary<string, list<string>>>
The problem is that json.net gives this error:
Error converting value "{" to type 'System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.String]]]'. Path 'resource_access', line 1, position 335. ---> System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.Dictionary`2[System.String,System.Collections.Generic.List`1[System.String]]].
The json validator at https://jsonformatter.curiousconcept.com/ lets this json pass as properly formatted, but I'm not sure it follows the standard to start with.
So, my question is: can this be deserialized without making a custom deserializer?

Related

JMS serializer - deserializing doctrine entity with reference by id not working

is it possible to deserialize this json object and set the "place" reference only by id in one request? :
{
"title": "some title",
"description" : "some description",
"place" : {
"id" : "5367ffcd3271d87f5c7b23cf" // mongoid to one-to-many reference object
}
}
in this case jms serializer giving me: Cannot create a DBRef without an identifier. UnitOfWork::getDocumentIdentifier() did not return an identifier for class Path\Document\Place (500 Internal Server Error)
Ok, i understand it. when i posting json object with properties like latitude, longitude and other than id everything working perfectly -> reference "child" Place object is created.
My question is -> what if i want to create reference with existing object only by indication via "id" in one single request using JMS with deserialize method?
Thanks for your help and sorry for my english.
i solved this by setting place object in #PostDeserialize action if isset place ID.

ASP.net how to use sessions?

I need to assign my variable to session. I tried this:
string name = string.Empty
Session["N"] = name;
and it won't work.
Error 1 Invalid token '[' in class, struct, or interface member declaration
Error 2 Invalid token '"N"' in class, struct, or interface member declaration
Error 3 Identifier expected
Where I'm wrong?
I'm using ASP.net in Visual Studio 2008.
Error 1 Invalid token '[' in class, struct, or interface member declaration
Error 2 Invalid token '"N"' in class, struct, or interface member declaration
Error 3 Identifier expected
missing ; end of first line.
string name = string.Empty;
Session["N"] = name;
string test= Session["N"].ToString();//Catch Your session
There is nothing wrong with that code (except a missing semicolon, as Shree Khanal pointed out, but that can't be the issue, right?).
As long as the code is in the page class, the Session property is available. If you have the code in a different class, you don't have the Session property available, then you need to get it from the current context:
HttpContext.Current.Session["N"] = name;
When reading the value from the session collection, the type is Object, not String, so you need to cast it:
string name = Session["N"] as string;
Using the as keyword means that you can attempt to read the value even if it would not exist, or if it happens to be set to a different data type. In that case you will get a null reference back.

ASP.NET Web Service returns IndexOutOfRangeException with arguments

I have the following web service:
[ScriptService]
public class Handler : WebService {
[WebMethod]
public void method1() {
string json = "{ \"success\": true }";
System.Web.HttpContext.Current.Response.Write(json);
}
[WebMethod]
public object method2(Dictionary<string, object> d) {
Dictionary<string, object> response = new Dictionary<string, object>();
response.Add("success", true);
return response;
}
}
The first method accepts a traditional html form post and response writes a JSON string to the page. The second method accepts a JSON value posted via AJAX and returns a serialized object.
Both these methods work fine on their own but when put together in the same web service I get this error when calling method1:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
When I remove the arguments from method2 they work.
Can anyone suggest why this is happening?
Edit:
The problem spans from the argument type of method2. If I change it to a string or simple data type it works fine. As Joel suggests it's probably because Dictionaries can't be serialized. This doesn't seem to affect my requests sent by ajax and only breaks direct form posts to this handler. Therefore my workaround is to put the form post handlers in a separate file by themselves. Not ideal but works for my application.
Dictionaries are not serializable. Hiding it behind an object doesn't do anything for you. You must first convert your dictionary to an array or some other serializable object before sending it out.
Why isn't there an XML-serializable dictionary in .NET?
http://weblogs.asp.net/pwelter34/archive/2006/05/03/444961.aspx
http://www.tanguay.info/web/index.php?pg=codeExamples&id=333

How can I deserialize elementary types from json in ASP.NET(System.Runtime.Serialization.Json)

I have a little problem.
When I'm using DataContractJsonSerializer with complex types(own types) it works fine. But I have to deserialize TimeStamp or DateTime from a string. So I cant mark these types with DataContract, DataMember attributes.
I wrote some code
string jsonedTS = "PT2M15S";
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(TimeSpan));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonedTS));
try {
result.Takes = (TimeSpan) jsonSerializer.ReadObject(ms);
} catch {
;
}
And I catch this Exception
{"There was an error deserializing the object of type System.TimeSpan. Encountered unexpected character 'P'."} System.Exception {System.Runtime.Serialization.SerializationException}
And My Question IS
How Can I deserialize
You can try with Json.Net library - it's worked pretty well for us in the past.

deserializing generic dictionary using json.net

I have a class looking like this:
class MyClass {
public int Id;
public Dictionary<int, MyClass[]> ChildValues;
}
when I try to deserialize this class using Json.NET:
MyClass x = return JsonConvert.DeserializeObject<MyClass>(s);
I receive the error Expected a JsonObjectContract or JsonDictionaryContract for type 'System.Collections.Generic.Dictionary`2[System.Int32,MyClass[]]', got 'Newtonsoft.Json.Serialization.JsonDictionaryContract'.
What does this error message mean and how can I resolve it?
Take a look at JSON you have in s variable first.
I found it. The problem was that the Json from the client was an array and not a dictionary (which in turn was because the script file was cached by IE).

Resources