Help with deserialzation???

21 views
Skip to first unread message

necker

unread,
Jan 8, 2009, 11:26:29 PM1/8/09
to Jayrock
This is my responce from Myspace
{
"totalResults":1,
"startIndex":1,
"itemsPerPage":1,
"sorted":false,
"filtered":false
"entry":[
{
"id":"myspace.com:26000010",
"nickname":"shaka",
"profileUrl":"http:\/\/www.myspace.com\/shakasarah",
"thumbnailUrl":"http:\/\/a229.ac-
images.myspacecdn.com\/images01\/118\/
s_3dcfafe8145a40fc46edacfebe7eaa94.jpg"
}
]
}
This is my Class

public class Person
{
public string fname { get; set; }
public string mname { get; set; }
public string lname { get; set; }

#region MySpace Properties
public string name { get; set; }
public string displayName { get; set; }
public string familyName { get; set; }
public string givenName { get; set; }
public string nickName { get; set; }
public string id { get; set; }
public string hasApp { get; set; }
public string[] emails { get; set; }
public DateTime dateOfBirth { get; set; }
public int age { get; set; }
#endregion

public static Person getjson(OAuth.Net.Consumer.OAuthResponse
response)
{
StreamReader irr = new StreamReader
(response.ProtectedResource.GetResponseStream());
string body = irr.ReadToEnd();
irr.Close();

Person deserializedPerson = (Person)
JavaScriptConvert.DeserializeObject(body, typeof(Person));
return deserializedPerson;


}

}

What id like to have is a array of objects or something of the such
that is stores each JSON entry array object for me to use to pass
around my code.
Thanks
Neil Ecker

Atif Aziz

unread,
Jan 9, 2009, 3:56:50 AM1/9/09
to jay...@googlegroups.com
Hi Neil,

Given your sample JSON, the way to achieve this would be to create a JsonTextReader over the source and then move through until you land on the "entry" member of the root object. Then you pull in the array value as Person objects. Here's how you could adapt your code to make this work:

public static Person[] getjson(TextReader input) {
using (JsonTextReader reader = new JsonTextReader(input)) {
do {} while (reader.Read()
&& (reader.Depth != 1
|| reader.TokenClass != JsonTokenClass.Member
|| !"entry".Equals(reader.Text, StringComparison.Ordinal)));
return reader.Read()
? (Person[]) JsonConvert.Import(typeof(Person[]), reader)
: new Person[0];
}
}

Here's what's going on...

do {} while (reader.Read()
&& (reader.Depth != 1
|| reader.TokenClass != JsonTokenClass.Member
|| !"entry".Equals(reader.Text, StringComparison.Ordinal)));

This loops until it finds a member called "entry" at depth 1. Next:

return reader.Read()
? (Person[]) JsonConvert.Import(typeof(Person[]), reader)
: new Person[0];

The Read positions the reader past the "entry" member and at its value. Then JsonConvert is used to de-serialize the member value as an array of Person objects. If the Read returns false, then it means the reader exhausted the input and never, in fact, found an "entry" member. In this case, a zero-length Person array is returned.

Hope this helps.

- Atif

necker

unread,
Jan 10, 2009, 1:43:48 AM1/10/09
to Jayrock
ok this is the error im getting now..
Cannot import OpenSocial.Person[] from a JSON Object value.

Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: Jayrock.Json.JsonException: Cannot import
OpenSocial.Person[] from a JSON Object value.

Source Error:


Line 92: || reader.TokenClass !=
JsonTokenClass.Member
Line 93: || !"entry".Equals(reader.Text,
StringComparison.Ordinal)));
Line 94: return reader.Read()
Line 95: ? (Person[])JsonConvert.Import
(typeof(Person[]), reader)
Line 96: : new Person[0];

Source File: E:\SocialCelebrityNet\UserAccess\App_Code\MySpace.cs
Line: 94

Stack Trace:


[JsonException: Cannot import OpenSocial.Person[] from a JSON Object
value.]
Jayrock.Json.Conversion.Converters.ImporterBase.ThrowNotSupported
(JsonTokenClass clazz) in J:\SocialCelebrityNet\jayrock\src
\Jayrock.Json\Json\Conversion\Converters\ImporterBase.cs:118
Jayrock.Json.Conversion.Converters.ImporterBase.ImportFromObject
(ImportContext context, JsonReader reader) in J:\SocialCelebrityNet
\jayrock\src\Jayrock.Json\Json\Conversion\Converters\ImporterBase.cs:
101
Jayrock.Json.Conversion.Converters.ImporterBase.Import
(ImportContext context, JsonReader reader) in J:\SocialCelebrityNet
\jayrock\src\Jayrock.Json\Json\Conversion\Converters\ImporterBase.cs:
83
Jayrock.Json.Conversion.ImportContext.Import(Type type, JsonReader
reader) in J:\SocialCelebrityNet\jayrock\src\Jayrock.Json\Json
\Conversion\ImportContext.cs:63
Jayrock.Json.Conversion.JsonConvert.Import(Type type, JsonReader
reader) in J:\SocialCelebrityNet\jayrock\src\Jayrock.Json\Json
\Conversion\JsonConvert.cs:106
UserAccess.MySpace.GetUserInfo(HttpContext context, Uri callback)
in E:\SocialCelebrityNet\UserAccess\App_Code\MySpace.cs:94
UserAccess._default.Page_Load(Object sender, EventArgs e) in E:
\SocialCelebrityNet\UserAccess\default.aspx.cs:36
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp,
Object o, Object t, EventArgs e) +15
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
sender, EventArgs e) +33
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +47
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+1436

necker

unread,
Jan 10, 2009, 2:57:25 AM1/10/09
to Jayrock
I Might have you confused on what i want. Once imported person[0]
would contain all the fields from the first entry object, if a second
entry object existed, person[1] would be made and hold all of those
and so on. so i could do something to get the value like person
[1].fullName....etc
Thanks
Neil

On Jan 9, 12:56 am, Atif Aziz <Atif.A...@skybow.com> wrote:

pete

unread,
Jan 10, 2009, 4:27:37 AM1/10/09
to Jayrock

Hi Neil

I think this should be easier if you can create your class to mirror
more closely what MySpace is sending you.

public class MySpaceResponse {
public int startIndex, totalResults, itemsPerPage;
public bool sorted, filtered;
public Person [ ] entry;
}

Then instead of fighting at a low level with trying to pick out parts
of the stream, you should be able to deserialize the whole response
with a single call, and the resulting object will have the array
you're trying to get at.

peter

necker

unread,
Jan 14, 2009, 4:23:30 PM1/14/09
to Jayrock
Ok no matter what I do i still get this error message.

Cannot import OpenSocial.MySpaceResponse[] from a JSON Object value.

I tried Atif's example to get to the "entry" node and still got the
same message except is was on my person[]

I like the idea that peter just gave that I could take the whole
response into a "object" and then have a array of persons in that
object. But i cant get it to work.

I will post my code below i have been working on this for 2weeks and
still cant get it to work.
Thanks for the help
Neil


JSON:

{
"totalResults":1,
"startIndex":1,
"itemsPerPage":1,
"sorted":false,
"filtered":false
"entry":[
{
"id":"myspace.com:26000010",
"nickname":"shaka",
"profileUrl":"http:\/\/www.myspace.com\/shakasarah",
"thumbnailUrl":"http:\/\/a229.ac-
images.myspacecdn.com\/images01\/118\/
s_3dcfafe8145a40fc46edacfebe7eaa94.jpg"
}
]
}

Class:
namespace OpenSocial
{
public class MySpaceResponse
{
public int startIndex, totalResults, itemsPerPage;
public bool sorted, filtered;
public Person[] entry;
}
public class Person
{
public string fname { get; set; }
public string mname { get; set; }
public string lname { get; set; }

#region MySpace Properties
public string name { get; set; }
public string displayName { get; set; }
public string familyName { get; set; }
public string givenName { get; set; }
public string nickName { get; set; }
public string id { get; set; }
public string hasApp { get; set; }
public string[] emails { get; set; }
public DateTime dateOfBirth { get; set; }
public int age { get; set; }
#endregion


}
}

Code: Note the commented lines that i have tried as well.

if (response.ProtectedResource.StatusDescription.Equals("OK"))
{
StreamReader json = new StreamReader
(response.ProtectedResource.GetResponseStream());


//MySpaceResponse[] MSR = (MySpaceResponse[])
JsonConvert.Import(typeof(MySpaceResponse[]), json);
//return MSR;


using (JsonTextReader reader = new JsonTextReader
(json))
{
do { } while (reader.Read()
&& (reader.Depth != 1
|| reader.TokenClass !=
JsonTokenClass.Member
|| !"entry".Equals(reader.Text,
StringComparison.Ordinal)));
return reader.Read()
? (MySpaceResponse[])JsonConvert.Import
(typeof(MySpaceResponse[]), reader)
: new MySpaceResponse[0];
}
}
else
return null;

Atif Aziz

unread,
Jan 15, 2009, 3:35:46 AM1/15/09
to jay...@googlegroups.com
> But i cant get it to work.

Neil, I just tried once more it's working perfectly fine, even with Peter's suggestion. I've attached the C# code I tested out. In case the attachment gets dropped, you can also find it online over at:

http://gist.github.com/47321

Compile it using:

csc jayrock-t4428c08b81d43485.cs /r:Jayrock.Json.dll

If all goes well then the nickname "shaka" should appear as the output of executing the program.

Could you kindly confirm this is also working on your end as well? Then we'll look at the possible source of the problem.

> i have been working on this for 2weeks and
> still cant get it to work.

That's unacceptable. I am sure we'll get it sorted very soon now. :)
jayrock-t4428c08b81d43485.cs

necker

unread,
Jan 15, 2009, 11:14:26 PM1/15/09
to Jayrock
Ok first of all I would like to thank all of you for the help. I have
figured out what the problem is it has something to do with my String
Data. Im getting the JSON from a OAuth response and i guess im not
converting it to a string properly. Again thank you for all your
help. Below is how im getting the string from the OAuth response.
Thanks for any insight.

StreamReader json = new StreamReader
(response.ProtectedResource.GetResponseStream());

Neil
> [jayrock-t4428c08b81d43485.cs2K ]using System;
> using Jayrock.Json.Conversion;
>
> class Program
> {
>         static void Main()
>         {
>             const string json = @"{
>             'totalResults':1,
>             'startIndex':1,
>             'itemsPerPage':1,
>             'sorted':false,
>             'filtered':false,
>             'entry':[
>             {
>                 'id':'myspace.com:26000010',
>                 'nickname':'shaka',
>                 'profileUrl':'http:\/\/www.myspace.com\/shakasarah',
>                 'thumbnailUrl':'http:\/\/a229.ac-images.myspacecdn.com\/images01\/118\/s_3d cfafe8145a40fc46edacfebe7eaa94.jpg'
>             }
>             ]
>         }";
>
>         var response = (MySpaceResponse) JsonConvert.Import(typeof(MySpaceResponse), json);
>         foreach (var person in response.entry)
>             Console.WriteLine(person.nickName);

necker

unread,
Jan 16, 2009, 12:35:08 AM1/16/09
to Jayrock

I have determined that the response that im getting from the stream
is:

{"entry":{"displayName":"Neil","name":
{"familyName":"Ecker","givenName":"Neil"},"dateOfBirth":"1979-04-05T00:00:00-07:00","emails":
[{"value":"ne...@eckerfamily.com","primary":true}],"profileUrl":"http:\/
\/www.myspace.com\/neilecker"}}

Not sure why im not getting the other values unless they are a header.

necker

unread,
Jan 19, 2009, 12:33:35 PM1/19/09
to Jayrock
I have figured out that the response has the "other values" contained
in the response object. also notice that the main problem is that the
response that im getting does not have the [] array after the entry
object, so its returning a single object not a array of objects like
noted on myspace. Does anyone know how to push this into a array[] or
check if it has a array value, i would like to use the same objects
for the singe response as a array of objects.

Thanks

On Jan 15, 9:35 pm, necker <neil.r.ec...@gmail.com> wrote:
> I have determined that the response that im getting from the stream
> is:
>
> {"entry":{"displayName":"Neil","name":
> {"familyName":"Ecker","givenName":"Neil"},"dateOfBirth":"1979-04-05T00:00:0 0-07:00","emails":
> [{"value":"n...@eckerfamily.com","primary":true}],"profileUrl":"http:\/

Atif Aziz

unread,
Jan 19, 2009, 12:59:35 PM1/19/09
to jay...@googlegroups.com
>>
Does anyone know how to push this into a array[] or
check if it has a array value, i would like to use the same objects
for the singe response as a array of objects.
<<

Depends on when you want to do this. You could import the entry as System.Object first and then check whether the actual imported type is IList or IDictionary. If it is IList, it's an ordered list of values (that's how Jayrock auto-imports a JSON array). If it's IDictionary then you have unordered key/value map. The other way would be to advance the reader to the "entry" member's value as I showed in one of the earlier posts and then check the JSON token type, whether it is an array or an object. Depending on that you could then import the value as Person or Person[]. I don't know the API you're dealing with so I am assuming your problem here is that "entry" is an array or an object depending on the API called. If I've misunderstood something or been unclear then let me know.

- Atif

-----Original Message-----
From: jay...@googlegroups.com [mailto:jay...@googlegroups.com] On Behalf Of necker
Sent: Monday, January 19, 2009 6:34 PM
To: Jayrock
Subject: [Jayrock] Re: Help with deserialzation???


Reply all
Reply to author
Forward
0 new messages