XML support and Object serialization

121 views
Skip to first unread message

RubySmith

unread,
Jan 29, 2009, 6:20:51 PM1/29/09
to Jayrock
Hello,
I'm new to JayRock,
I am trying to port Java code to C# particularly the JSON functions.
I have the following two code snippets in java ( written using
org.json.JSONObject package)

1)
JSONObject jsonObject = new JSONObject(this);
return jsonObject.toString();

2)
String xml = "some xml doc";
JSONObject root = XML.toJSONObject(xml);
Iterator<String> iterator = root.keys();
JSONObject json = root.getJSONObject(iterator.next());

How can i port them to C# using JayRock APIs? I could not find API doc
on the site.
Does JSON.NET a better choice?
I want to support .NET 2.0 and upwards if not .NET 1.1

Thanks a lot in advance,
-RS

Atif Aziz

unread,
Jan 30, 2009, 3:03:30 AM1/30/09
to jay...@googlegroups.com
How does your current Java library map the XML to JSON? Jayrock currently supports JsonML, which is just one of the many ways to map XML to JSON and vice versa. If you're happy with that then Jayrock may just do the job for you. I don't know much JSON.NET's XML-to-JSON conversion. You may have to investigate that on your own.

- Atif

Pudur Ramaswamy

unread,
Jan 30, 2009, 1:09:54 PM1/30/09
to jay...@googlegroups.com
Thanks for the Reply. Java library is a third pary library and API docs tells exactly what it does support and the code snippet i gave you gives a pretty good idea of its XML to JSON support.
 
where can i learn more about JsonML?  Is there a online API doc? Particulaly how can i port the following code to C# using your APIs?
 
String xml = "some xml content";
JSONObject root = XML.toJSONObject(xml);
Iterator<String> iterator = root.keys();
JSONObject json = root.getJSONObject(iterator.next());

Thanks,
-p
 

Pudur Ramaswamy

unread,
Jan 30, 2009, 6:03:49 PM1/30/09
to jay...@googlegroups.com
I think your AutoImportDemo will do the trick.... Thanks...

Does JSonObject has IsNull method? Not having API doc is making the learning harder for me..

-p

 

Pudur Ramaswamy

unread,
Feb 2, 2009, 2:08:17 PM2/2/09
to jay...@googlegroups.com
Sorry I'll take it back. It (AutoImportDemo) only does Json format text to Jason Object and that is not what i need.
 
I'd appreciate if you could provide me some more pointers on using JasonML and your library. I like your library becuse it supports .NET 1.1 also.
 
 
Thanks,
-pudur

 

Atif Aziz

unread,
Feb 3, 2009, 3:24:02 AM2/3/09
to jay...@googlegroups.com
> I'd appreciate if you could provide me some more pointers
> on using JasonML and your library.

I've attached a demo program that shows encoding XML into JSON using JsonML and then re-creating the XML.

If the attachment is removed, you can also find the source online over at:
http://gist.github.com/57409

Hope this helps,
Atif
<br
JsonMLDemo.cs

Pudur Ramaswamy

unread,
Feb 4, 2009, 8:16:18 PM2/4/09
to jay...@googlegroups.com
Thanks for the info. I was not able compile it. I get:
Error 1 The type or namespace name 'JsonML' does not exist in the namespace 'Jayrock' (are you missing an assembly reference?) C:\myCsharpProjects\ConsoleApplication2\ConsoleApplication2\Program.cs 5 15 ConsoleApplication2
where can i download your DLL? I dowload 0.9.8316 version from http://developer.berlios.de/project/showfiles.php?group_id=4638
 
So this is what my understanding is: ( Please correct if i'm worng)
So once you convert a xml fragment or whole xml document to JsonML format, you can get Json text and using json text we can get JSON pbjects. Right?
-RS
 


 

       {
           const string @xml = @"
<div id='demo' class='JSONML'><p>JSONML is a transformation
between<b>JSON</b>and<b>XML</b>that preserves ordering of document
features.</p><p>JSONML can work with JSON arrays or JSON
objects.</p><p>Three<br/>little<br/>words</p></div>";

           StringWriter jsonw = new StringWriter();

           new JsonMLEncoder().Encode(
               new XmlTextReader(new StringReader(xml)),
               new JsonTextWriter(jsonw));

       Console.WriteLine(jsonw);

       StringWriter xmlw = new StringWriter();

       new JsonMLDecoder().Decode(
           new JsonTextReader(new StringReader(jsonw.ToString())),
           new XmlTextWriter(xmlw));

       Console.WriteLine(xmlw);
       }
}


Atif Aziz

unread,
Feb 5, 2009, 3:56:41 AM2/5/09
to jay...@googlegroups.com
>>
Error 1 The type or namespace name 'JsonML' does not exist in the namespace 'Jayrock' (are you missing an assembly reference?) C:\myCsharpProjects\ConsoleApplication2\ConsoleApplication2\Program.cs 5 15 ConsoleApplication2
where can i download your DLL? I dowload 0.9.8316 version from http://developer.berlios.de/project/showfiles.php?group_id=4638
<<

That version does not have JsonML support. Use the latest developer build (equally stable) from:
ftp://ftp.berlios.de/pub/jayrock

>>
So once you convert a xml fragment or whole xml document to JsonML format, you can get Json text and using json text we can get JSON pbjects. Right?
<<

Yep, you got it. :)

Pudur Ramaswamy

unread,
Feb 5, 2009, 2:02:28 PM2/5/09
to jay...@googlegroups.com
It works now. Thanks..I'll play with it more with my xml code fragment and JSON object APIs of yours to know how it goes.
Though your APIs provide the solutiion though not as elegant as the one provided by Java library org.jason.* packages, that might solve my problem. I'm sure some one will come up with that solution for .NET soon.
Thanks again,
-RS

Atif Aziz

unread,
Feb 5, 2009, 6:48:54 PM2/5/09
to jay...@googlegroups.com

> though not as elegant as the one provided by Java library org.jason.* packages

 

Would you care to expand on which bits you find inelegant or inconvenient?

Atif Aziz

unread,
Feb 5, 2009, 6:51:36 PM2/5/09
to jay...@googlegroups.com
>> though not as elegant as the one provided by Java library org.jason.* packages

> Would you care to expand on which bits you find inelegant or inconvenient?

I mean, I'm sure there's room for improvement. :)

- Atif

Pudur Ramaswamy

unread,
Feb 6, 2009, 12:42:52 PM2/6/09
to jay...@googlegroups.com
I meant the extra step of converting xml to JsonML and then to json object from an xml snippet vs xml to json object straight.
 
-RS

RubySmith

unread,
Feb 18, 2009, 2:05:39 PM2/18/09
to Jayrock
Hi Atif,

As per your example, how can i get JasonArray and JsonObjects form
Json text ( jsonw)
The following works:

JsonArray items = (JsonArray)JsonConvert.Import(jsonw.ToString());

when i iterate the array, how do i know what to cast for ewach item in
the array? Having an NDOC would be beneficial.

So my question is we can only get JsonArray from jsonw? How can i get
equivalent of Jsonobject?

The success of this library is in critical path of a new project i
undertook. I'd greatly appreciate your help to ovecome my hurdles,
that is to get JsonObject and use the methods on it.

Thanks a lot,
-p



On Feb 5, 12:56 am, Atif Aziz <Atif.A...@skybow.com> wrote:
> Error 1 The type or namespace name 'JsonML' does not exist in the namespace 'Jayrock' (are you missing an assembly reference?) C:\myCsharpProjects\ConsoleApplication2\ConsoleApplication2\Program.cs 5 15 ConsoleApplication2
> where can i download your DLL? I dowload 0.9.8316 version fromhttp://developer.berlios.de/project/showfiles.php?group_id=4638
> <<
>
> That version does not have JsonML support. Use the latest developer build (equally stable) from:ftp://ftp.berlios.de/pub/jayrock
>
>
>
> So once you convert a xml fragment or whole xml document to JsonML format, you can get Json text and using json text we can get JSON pbjects. Right?
> <<
>
> Yep, you got it. :)
>
> From: jay...@googlegroups.com [mailto:jay...@googlegroups.com] On Behalf Of Pudur Ramaswamy
> Sent: Thursday, February 05, 2009 2:16 AM
> To: jay...@googlegroups.com
> Subject: [Jayrock] Re: XML support and Object serialization
>
> Thanks for the info. I was not able compile it. I get:
> Error 1 The type or namespace name 'JsonML' does not exist in the namespace 'Jayrock' (are you missing an assembly reference?) C:\myCsharpProjects\ConsoleApplication2\ConsoleApplication2\Program.cs 5 15 ConsoleApplication2
> where can i download your DLL? I dowload 0.9.8316 version fromhttp://developer.berlios.de/project/showfiles.php?group_id=4638
> }- Hide quoted text -
>
> - Show quoted text -

Pudur Ramaswamy

unread,
Feb 18, 2009, 2:41:15 PM2/18/09
to Jayrock
also,
The following xml (WSDL) segment can not be converted. It complains about xs namespace
<xs:complexType name="MyRequest">
<xs:annotation>
<xs:documentation>
 This is the sample message
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs="1" name="requestEnvelope"
 type="common:RequestEnvelope" />
<xs:element minOccurs="1" maxOccurs="1"
 name="email" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="transactionId" type="xs:string"/>
<xs:element minOccurs="0" maxOccurs="1" name="trackingId" type="xs:string"/>
<xs:any maxOccurs="unbounded" minOccurs="0"
 namespace="##other" processContents="lax" />
</xs:sequence>
</xs:complexType>

Atif Aziz

unread,
Feb 19, 2009, 4:03:35 AM2/19/09
to jay...@googlegroups.com
> when i iterate the array, how do i know what
> to cast for ewach item in the array?

You use regular C# stuff here to check the type of the object at run-time. Here is translation that occurs when you don't specify any type to JsonConver.Import:

JSON "null" -> null
JSON "true" -> bool with the value true
JSON "false" -> bool with the value false
JSON Number -> JsonNumber/IConvertible
JSON String -> string
JSON Array -> JsonArray/IList
JSON Object -> JsonObject/IDictionary

Given the above, you do can do a run-time check like this assuming some index into an items array:

JsonObject obj = items[index] as JsonObject;
if (obj != null) {
// Do something with object
}

If you prefer to work with general types and protocols to keep your code flexible (and free of Jayrock types) then you can also work with the interfaces shown above. So for an object, just pretend it is IDictionary, which JsonObject implements:

IDictionary obj = items[index] as IDictionary;
if (obj != null) {
// Do something with object...
}

JsonNumber is special. Jayrock does not pretend to make conversions on your behalf like many other libraries that take a trial & error approach. Jayrock delivers JSON numbers as JsonNumber. You then decide how you want to crack it. For this, JsonNumber supports explicit casting, so you can just do this:

if (items[index] is JsonNumber) {
long l = (long) (JsonNumber) items[index];
// Do something with long integer...
}

Again, if you prefer, you can also work with the IConvertible interface:

if (items[index] is IConvertible) {
long l = ((IConvertible) items[index]).ToInt64();
// Do something with long integer...
}

Note, however, that a System.String also implements IConvertible, so you have to make sure you are not dealing with a string before resorting to IConvertible for numbers. Of course, if you already know the type of numbers you are expecting, then you don't have to go over JsonNumber. You can just do this:

int[] nums = JsonConvert.Import(typeof(int[]), "[1,2,3]");

> Having an NDOC would be beneficial.

Documentation is sore point. Meanwhile, I am here to help. :)

Atif Aziz

unread,
Feb 19, 2009, 4:06:14 AM2/19/09
to jay...@googlegroups.com
> The following xml (WSDL) segment can not be converted.
> It complains about xs namespace

Even within fragments, XML namespaces should be known. This is more about XML Jayrock.
It may help to share the code as an isolated and self-contained example.

- Atif

Pudur Ramaswamy

unread,
Feb 19, 2009, 1:24:51 PM2/19/09
to jay...@googlegroups.com
Thank you very much for prompt reply.
 
So what will be the sturcture of the JsonObject after the statement given below for JayRock? It looks to me we get one obj which is a JsonObject for each item in the array? Does JayRock only provide only JsonArray for the xml fragment? As i mentioned earlier Java libray just works fine for the xml fragment whereas JayRock complains about the namespace. I
 
JayRock:
JsonObject obj = items[index] as JsonObject;
if (obj != null) {
 // Do something with object
}
for the xml fragment i posted earlier, the following code throws XmlException was unhandled: xs is an undeclared namespace. Line 1, position 2.
new JsonMLEncoder().Encode(new XmlTextReader(new StringReader(xml)),new JsonTextWriter(jsonw));
 
as part of our porject, while parsing the WSDL elements for Types, we just pass the element node to get JSON equivalent, at that time we have no control to add namespace. Java library just works fine for the same xml fragment.
 
Let me know if  there is a way we can work around this issue?
Thanks,

RubySmith

unread,
Feb 19, 2009, 7:26:06 PM2/19/09
to Jayrock
Looks like, there is a way to get rid of namespace issue as
recommended by .NET SDK team
http://bytes.com/groups/net-xml/455275-xml-fragment-undeclared-namespace


On Feb 19, 10:24 am, Pudur Ramaswamy <pudur.ramasw...@gmail.com>
wrote:
> > you. I don't know much JSON.NET <http://json.net/>'s XML-to-JSON
> > conversion. You may have to investigate that on your own.
>
> > > - Atif
>
> > > -----Original Message-----
> > > From: jay...@googlegroups.com [mailto:jay...@googlegroups.com] On
> > Behalf Of RubySmith
> > > Sent: Friday, January 30, 2009 12:21 AM
> > > To: Jayrock
> > > Subject: [Jayrock] XML support and Object serialization
>
> > > Hello,
> > > I'm new to JayRock,
> > > I am trying to port Java code to  C# particularly the JSON functions.
> > > I have the following two code snippets in java ( written using
> > > org.json.JSONObject package)
>
> > > 1)
> > > JSONObject jsonObject = new JSONObject(this);
> > > return jsonObject.toString();
>
> > > 2)
> > > String xml = "some xml doc";
> > > JSONObject root = XML.toJSONObject(xml);
> > > Iterator<String> iterator = root.keys();
> > > JSONObject json = root.getJSONObject(iterator.next());
>
> > > How can i port them to C# using JayRock APIs? I could not find API doc
> > > on the site.
> > > Does JSON.NET <http://json.net/> a better choice?
> > > I want to support .NET 2.0 and upwards if not .NET 1.1
>
> > > Thanks a lot in advance,
> > > -RS
> > > <br
>
> > >        {
> > >            const string @xml = @"
> > > <div id='demo' class='JSONML'><p>JSONML is a transformation
> > > between<b>JSON</b>and<b>XML</b>that preserves ordering of document
> > > features.</p><p>JSONML can work with JSON arrays or JSON
> > > objects.</p><p>Three<br/>little<br/>words</p></div>";
>
> > >            StringWriter jsonw = new StringWriter();
>
> > >            new JsonMLEncoder().Encode(
> > >                new
>
> ...
>
> read more »- Hide quoted text -

Atif Aziz

unread,
Feb 20, 2009, 3:29:21 AM2/20/09
to jay...@googlegroups.com

Try turning off XML namespaces support on the XmlTextReader object by setting its Namespaces property to false.

See attached demo that shows how you can parse the XSD fragment you pasted in your post.

You can also find it online here along with the output JSON:

http://gist.github.com/67375

 

- Atif

JsonMLDemo.cs

Pudur Ramaswamy

unread,
Feb 20, 2009, 8:44:17 PM2/20/09
to jay...@googlegroups.com
Thank you for the neat trick to overcome the namespace issue. However, i can only get JsonArray representation of the xml fragment.
Can you point me to the API docs or tell me how can i find "name" element is present or not in the sequence? In otherwords what methods of JsonArray will tell me whether there is a name element in the ComplexType? the solution must be generic not specific to this code. Obviously contains method did not work for me as i'm clear on the array structure..

StringWriter

jsonw = new StringWriter();

XmlTextReader reader = new XmlTextReader(new StringReader(xml));

reader.Namespaces =

false;

JsonMLCodec.Encode(reader, new JsonTextWriter(jsonw));

JsonArray items = (JsonArray)JsonConvert.Import(jsonw.ToString()); if (items.contains("name") ) --->  returns false

   public static void Main()

   {
       const string @xml = @"
<xs:complexType name='MyRequest'>
<xs:annotation>
<xs:documentation>
 This is the sample message
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs='1' name='requestEnvelope'
 type='common:RequestEnvelope' />
<xs:element minOccurs='1' maxOccurs='1'
 name='email' type='xs:string' />
<xs:element minOccurs='0' maxOccurs='1' name='transactionId' type='xs:string'/>
<xs:element minOccurs='0' maxOccurs='1' name='trackingId' type='xs:string'/>
<xs:any maxOccurs='unbounded' minOccurs='0'
 namespace='##other' processContents='lax' />
</xs:sequence>
</xs:complexType>";


       StringWriter jsonw = new StringWriter();
       XmlTextReader reader = new XmlTextReader(new StringReader(xml));
       reader.Namespaces = false;

       JsonMLCodec.Encode(reader, new JsonTextWriter(jsonw));

       Console.WriteLine(jsonw);
   }
}


Pudur Ramaswamy

unread,
Feb 23, 2009, 5:48:14 PM2/23/09
to jay...@googlegroups.com
Hi Atif,
The JSON ouput looks good. What is the best way to represent that string as JSON Object?
Thanks,
-p


   public static void Main()

   {
       const string @xml = @"
<xs:complexType name='MyRequest'>
<xs:annotation>
<xs:documentation>
 This is the sample message
</xs:documentation>
</xs:annotation>
<xs:sequence>
<xs:element minOccurs='1' name='requestEnvelope'
 type='common:RequestEnvelope' />
<xs:element minOccurs='1' maxOccurs='1'
 name='email' type='xs:string' />
<xs:element minOccurs='0' maxOccurs='1' name='transactionId' type='xs:string'/>
<xs:element minOccurs='0' maxOccurs='1' name='trackingId' type='xs:string'/>
<xs:any maxOccurs='unbounded' minOccurs='0'
 namespace='##other' processContents='lax' />
</xs:sequence>
</xs:complexType>";


       StringWriter jsonw = new StringWriter();

Atif Aziz

unread,
Feb 24, 2009, 2:21:22 AM2/24/09
to jay...@googlegroups.com

As I said before, JSON objects become IDictionary objects and JSON arrays become IList objects. These are standard .NET interfaces you need to be familiar with. There is nothing Jayrock-ish about them. You need to get familiar with JsonML and XML gets transformed into it. This is also well-documented at http://jsonml.org. Which other part are you having trouble particular with otherwise?

Reply all
Reply to author
Forward
0 new messages