JsonContentHandler.cs
2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//*************************************************************************************************
// JsonContentHandler.cs
// Owner: Mahipal Kante
//
// Encode/decode JSON format for Web Service response. converts JSON into XML back and forth
//
// Copyright(c) Microsoft Corporation, 2010
//*************************************************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Xml.XPath;
namespace WebTest.WebService.Plugin.Runtime
{
public class JsonContentHandler : ContentHandler
{
public override string MessageString
{
get
{
string message = string.Empty;
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
using (var stream = new MemoryStream())
{
using (XmlDictionaryWriter writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
{
this.XmlDocument.WriteTo(writer);
}
message = encoding.GetString(stream.ToArray());
}
return message;
}
set
{
this.jsonMessage = value;
this.XmlString = string.Empty;
}
}
public override XPathDocument XPathDocument
{
get
{
return new XPathDocument(GetReader());
}
}
protected override void LoadDocument()
{
try
{
this.XmlDocument = new XmlDocument();
this.XmlDocument.Load(GetReader());
}
catch (Exception)
{
// try setting it as an XML
this.XmlString = jsonMessage;
}
}
private XmlDictionaryReader GetReader()
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
XmlDictionaryReader jsonReader =
System.Runtime.Serialization.Json.JsonReaderWriterFactory.CreateJsonReader(
encoding.GetBytes(this.jsonMessage),
XmlDictionaryReaderQuotas.Max);
return jsonReader;
}
private string jsonMessage = string.Empty;
}
}