472,958 Members | 2,358 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,958 software developers and data experts.

JSON deserialization using DataContractJsonSerializer

Hi,

I am using DataContractJsonSerializer to deserialize JSON string in C#
objects but I am having a problem.

Suppose I have a class:

class Item
{
public ItemId Id { get; set; }
}

class ItemId
{
public int Value { get; set; }
}
The JSON string for a Item object looks like this:

{ "Id": 100 }

The deserialization does not work since it expects that Id member is of type
int.
Even if I add a constructor like this:

class ItemId
{
public ItemId(int v)
{
Value = v;
}
public int Value { get; set; }
}

deserialization still doesn't work.

There are some workarounds like chaning the JSON and add Value but I don't
want that.

Is there a way to make deserialization to create the ItemId directly from
int ?

Thaks
Oct 23 '08 #1
7 16074
Well, you could use a different member for the serialization?

[DataContract]
class Item {
public ItemId Id {get;set;}

[DataMember(Name="Id")]
private int SerializationId {
get {return Id.Value;}
set {Id = new ItemId(value);}
}
}

That do?

Marc
Oct 23 '08 #2
What framework are you using? The following (below) works fine for me...

You can always make it public and use [Browsable(false)] and
[EditorBrowsable(EditorBrowsableState.Never)] to make it less visible?

Marc
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.ComponentModel;
[DataContract]
class Item
{
public ItemId Id { get; set; }

[DataMember(Name = "Id")]
public int SerializationId
{
get { return Id.Value; }
set { Id = new ItemId(value); }
}

static void Main()
{
DataContractJsonSerializer json = new
DataContractJsonSerializer(typeof(Item));
using(MemoryStream ms = new MemoryStream()) {
Item item = new Item { Id = new ItemId(4) };
json.WriteObject(ms, item);
ms.Position = 0;
string txt = Encoding.UTF8.GetString(ms.GetBuffer(), 0,
(int)ms.Length);
item = (Item)json.ReadObject(ms);
System.Console.WriteLine(item.Id.Value);
}
}
}

struct ItemId
{
private readonly int value;
public int Value { get { return value; } }
public ItemId(int value) { this.value = value; }
}
Oct 23 '08 #3
It works fine for you because you use public access for SerializationId.
Initially you give me the idea to use private and it doesn't work.

Using [Browsable(false)] and [EditorBrowsable(EditorBrowsableState.Never)]
is not an option.

It seems the only option I have is to have 2 public properties which is not
nice.

Thanks.
"Marc Gravell" <ma**********@gmail.comwrote in message
news:ee**************@TK2MSFTNGP04.phx.gbl...
What framework are you using? The following (below) works fine for me...

You can always make it public and use [Browsable(false)] and
[EditorBrowsable(EditorBrowsableState.Never)] to make it less visible?

Marc
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.ComponentModel;
[DataContract]
class Item
{
public ItemId Id { get; set; }

[DataMember(Name = "Id")]
public int SerializationId
{
get { return Id.Value; }
set { Id = new ItemId(value); }
}

static void Main()
{
DataContractJsonSerializer json = new
DataContractJsonSerializer(typeof(Item));
using(MemoryStream ms = new MemoryStream()) {
Item item = new Item { Id = new ItemId(4) };
json.WriteObject(ms, item);
ms.Position = 0;
string txt = Encoding.UTF8.GetString(ms.GetBuffer(), 0,
(int)ms.Length);
item = (Item)json.ReadObject(ms);
System.Console.WriteLine(item.Id.Value);
}
}
}

struct ItemId
{
private readonly int value;
public int Value { get { return value; } }
public ItemId(int value) { this.value = value; }
}

Oct 23 '08 #4
>It works fine for you because you use public access
>for SerializationId.
That was actually a hangover from trying the [Browsable] etc. Sorry for
the confusion, but it works fine for me "private" too.

Are you using CF/Silverlight? In regular .NET, DataContractSerializer
(and JSON) works with public *and* non-public members.

Marc
Oct 23 '08 #5
Oh, okay, I see what you mean now :)
Yes, I am trying to make it work in Silverlight 2 RTM
Is there any way without making both properties public ?
"Marc Gravell" <ma**********@gmail.comwrote in message
news:Oy*************@TK2MSFTNGP02.phx.gbl...
It works fine for you because you use public access
for SerializationId.

That was actually a hangover from trying the [Browsable] etc. Sorry for
the confusion, but it works fine for me "private" too.

Are you using CF/Silverlight? In regular .NET, DataContractSerializer (and
JSON) works with public *and* non-public members.

Marc

Oct 23 '08 #6
Is there any way without making both properties public ?

At a *push*, maybe a surrogate (IDataContractSurrogate), but I kinda
suspect that it won't exist in Silverlight, and it is also a *lot* of
work. Silverlight is *very* picky about member access / reflection - so
it you want the flat serialization but a structured object model, you
are going to have to compromise with some unsightly (extra) public
properties (ideally with the "hide me" attributes to make them less
annoying).

Marc
Oct 23 '08 #7
Thanks alot for the insights.
I will have to live with the extra public property and I will try to use the
suggested attributes.

Another (ugly) solution is to have 2 separate objects, internal one for
deserialization and a public one for client use.
The public one will hold inside the internal one and forward properties to
it.

What do you think ?

"Marc Gravell" <ma**********@gmail.comwrote in message
news:%2****************@TK2MSFTNGP06.phx.gbl...
Is there any way without making both properties public ?

At a *push*, maybe a surrogate (IDataContractSurrogate), but I kinda
suspect that it won't exist in Silverlight, and it is also a *lot* of
work. Silverlight is *very* picky about member access / reflection - so it
you want the flat serialization but a structured object model, you are
going to have to compromise with some unsightly (extra) public properties
(ideally with the "hide me" attributes to make them less annoying).

Marc

Oct 23 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: George Jempty | last post by:
In my journal anyway: "JSON: Javascript Unusable by the Client" http://slashdot.org/~scriptify/journal/103074
16
by: G Matthew J | last post by:
http://htmatters.net/htm/1/2005/07/evaling-JSON.cfm This is more or less in response to Mr Crockford's admonition a few months ago, "fork if you must". Ironically, although in that usenet post...
20
by: Luke Matuszewski | last post by:
Welcome As suggested i looked into JSON project and was amazed but... What about cyclical data structures - anybody was faced it in some project ? Is there any satisactional recomendation... ...
2
by: ChrisO | last post by:
I've been pretty infatuated with JSON for some time now since "discovering" it a while back. (It's been there all along in JavaScript, but it was just never "noticed" or used by most until...
23
by: dhtmlkitchen | last post by:
JSON We all know what it is. In ECMAScript 4, there's a JSON proposal: Object.prototype.toJSONString String.prototype.parseJSON The current proposal, String.prototype.parseJSON, returns...
2
by: vunet | last post by:
When implementing JSON as a form of data exchange between server and client, what security measures do I need to consider? For example, I have XMLHttpRequest returning JSON text from the server and...
4
by: =?Utf-8?B?UmFqaXYgVmVybWE=?= | last post by:
Hi, I am using .NET 3.5 JSON deserializer. When I am passing my JSON server response to DataContractJsonSerializer, DataContractJsonSerializer ser = new...
1
by: =?Utf-8?B?QmlsbHkgWmhhbmc=?= | last post by:
I have a asp.net app, in client I create a Complicate json string, for example: { a: ‘a’, b : { b ; ‘b’ } } If .net has corresponding type, it could be deserialized, for example: ...
0
by: Nightcrawler | last post by:
I am trying to deserialize a simple string using the following method: private object JSONDeserialize(string DeserializationTarget, Type TargetType) { MemoryStream ms = new...
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
0
tracyyun
by: tracyyun | last post by:
Hello everyone, I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
4
NeoPa
by: NeoPa | last post by:
Hello everyone. I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report). I know it can be done by selecting :...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.