473,387 Members | 1,420 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 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 16112
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...

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.