WCF, Serialize Json to XML - json

Using DataContractJsonSerializer, I was able to get Json string.
Now, I want to convert this Json(named 'stream') to XML.
Is there any way without using "[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped)]"?
IService
[OperationContract]
string JsonSerializeFromDatabase();
[OperationContract]
string XmlSerializeFromJson(string strJson);
ClientSide
WCFService.Service1Client client = new WCFService.Service1Client();
string stream = client.JsonSerializeFromDatabase();
string stream2 = client.XmlSerializeFromJson(stream);
div1.InnerText = stream2;
ServerSide that I currently have (but no luck)
public string XmlSerializeFromJson(string strJson)
{
Stream stream1 = new FileStream("temp.xml", FileMode.Create);
XmlWriter xmlWriter = XmlWriter.Create(stream1);
XmlSerializerser = new XmlSerializer(typeof(string));
ser.Serialize(xmlWriter, strJson);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
string strXml = sr.ReadToEnd();
stream1.Dispose();
stream1.Close();
return strXml;
}

You need to first deserialize your json string into an instance of a type, and then create the serializer specifically to serialize the instance of the type to xml.
Something like:
var myInstance = new JavaScriptSerializer().Deserialize<InstanceType>(strJson);
var ser = new XmlSerializer(typeof(InstanceType));
ser.Serialize(xmlWriter, myInstance);

Related

invalid utf-8 start byte 0xb0

In Java, I am adding some properties to a JSON object, and sending those values to an HTTPS URL (REST API). The server throws some error like "invalid utf-8 start byte 0xb0". Below is my code:
final String urlString = "https://connect.pointclickcare.com/api/public/preview1/orgs/"+vitalStat.get("customer")+"/observations";
String authorization = "Bearer "+vitalStat.get("accessToken");
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", vitalStat.get("type"));
jsonObject.addProperty("patientId", patientInfo.getPatientId());
jsonObject.addProperty("deviceId", vitalStat.get("deviceId"));
jsonObject.addProperty("deviceName", vitalStat.get("deviceName"));
jsonObject.addProperty("recordedDate", vitalStat.get("recordedDate"));
jsonObject.addProperty("value", vitalStat.get("value"));
jsonObject.addProperty("method", vitalStat.get("method"));
if(vitalStat.get("type").equals("temperature"))
{
jsonObject.addProperty("unit", "°F");
}
else{
jsonObject.addProperty("unit", vitalStat.get("unit"));
}
if(vitalStat.get("type").equals("bloodPressure"))
{
String[] split = vitalStat.get("value").split("/");
jsonObject.addProperty("systolicValue", split[0]);
jsonObject.addProperty("diastolicValue", split[1]);
jsonObject.remove("value");
}
HttpURLConnection connection = null;
try {
final URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HttpMethod.POST);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",MediaType.APPLICATION_JSON);
connection.setRequestProperty("Accept", MediaType.APPLICATION_JSON);
connection.setRequestProperty("Authorization", authorization);
final OutputStream outputStream = connection.getOutputStream();
final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeBytes(jsonObject.toString());
dataOutputStream.close();
System.out.println(connection.getResponseMessage());
You don't want to use DataOutputStream. It has its own data encoding and is certainly not compatible with JSON. Instead, you have to serialize your JSON data such that a string representation of JSON (in UTF-8) is generated.
I assume that you are using JsonObject from org.json. In that case, the code should looks something like this:
final OutputStream outputStream = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
jsonObject.write(writer);

Unable to use DataContractJsonSerializer in Xamarin.Mac

I was using the following to convert my properties to JSON in windows and it is working very well but now I am trying to do the same in Xamarin on my Mac but it is unable to recognize DataContractJsonSerializer. Below is the code i was using on windows:
public static string JsonSerializer(T t)
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, t);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
//Replace Json Date String
string p = #"\\/Date\((\d+)\+\d+\)\\/";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertJsonDateToDateString);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
return jsonString;
}
Can anyone in finding a workaround so that i can use this in my Xamarin.Mac project.
Solved problem by myself. I used Json.Net like this:
//Convert "yyyy-MM-dd HH:mm:ss" String as "\/Date(1319266795390+0800)\/"
string p = #"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
MatchEvaluator matchEvaluator = new MatchEvaluator(ConvertDateStringToJsonDate);
Regex reg = new Regex(p);
jsonString = reg.Replace(jsonString, matchEvaluator);
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
Newtonsoft.Json.JsonSerializer serializer = new JsonSerializer();
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
JsonReader reader = new JsonTextReader(new StreamReader(ms));
T obj2 = serializer.Deserialize<T>(reader);
//T obj = (T)ser.ReadObject(ms);
return obj2;
Results are same.

Is it possible to use JsonReaderWriterFactory to convert XML to JSON without using DataContractJsonSerializer?

I need a generic routine that takes any valid XML and converts it to JSON without knowing the underlying data type. I know that this is easily done with Json.Net and I also know how to do it with the DataContractJsonSerializer but our organisation doesn't use Json.Net and the DataContractJsonSerializer needs a Data Contract enabled object type.
My working code using Json.Net:
XmlDocument document = new XmlDocument();
document.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(document);
The code I'd like to be able to use, using JsonReaderWriterFactory instead of Json.Net:
string jsonText = string.Empty;
MemoryStream stream = new MemoryStream();
StreamWriter streamWriter = new StreamWriter(stream);
streamWriter.Write(xml);
streamWriter.Flush();
stream.Position = 0;
using (XmlDictionaryWriter xmlWriter = JsonReaderWriterFactory.CreateJsonWriter(stream))
{
object someObject = new object();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(someObject.GetType());
serializer.WriteObject(stream, someObject);
xmlWriter.Flush();
jsonText = Encoding.Default.GetString(stream.GetBuffer());
}
Is there a way around this?
Too bad the Json.Net isn't an option - we've used it for years now, and it's fantastic. Short of native parsing and json generation by hand, there's not a lot of fast ways to do this.
Check out the code from this link:
http://www.phdcc.com/xml2json.htm (See section "XmlToJSON C# code", should be fairly quick)
This code could easily be adapted to a class or even extension to convert an XML Document (or even just xml string being parsed into an XML document, then returning the json.
Another approach to consider could be the following. It specifies using anonymous types assuming you don't have control of the objects that could be deserialized from XML (and you don't want to manage those separate types).
Convert the XML into an anonymous type (probably through the
Use the JavascriptSerializer to serialize the anonymous object into the json
The code sample below shows this techinique:
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Data.Entity.Design.PluralizationServices;
using System.Globalization;
namespace Scratch
{
class Program
{
static void Main(string[] args)
{
string xml = "<root><student><id>1</id></student><student><id>2</id></student></root>";
string json = XmlToJson(xml);
Console.WriteLine(json);
Console.ReadKey(true);
}
// Using JavaScriptSerializer
static string XmlToJson(string xml)
{
var obj = GetAnonymousType(xml);
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Serialize(obj);
}
// Adapted from: http://www.codeproject.com/Tips/227139/Converting-XML-to-an-dynamic-object-using-ExpandoO
static dynamic GetAnonymousType(string xml, XElement node = null)
{
node = string.IsNullOrEmpty(xml) ? node : XDocument.Parse(xml).Root;
IDictionary<String, dynamic> result = new ExpandoObject();
var pluralizationService = PluralizationService.CreateService(CultureInfo.CreateSpecificCulture("en-us"));
node.Elements().AsParallel().ForAll(gn =>
{
var isCollection = gn.HasElements
&& (gn.Elements().Count() > 1
&& gn.Elements().All(e => e.Name.LocalName.ToLower() == gn.Elements().First().Name.LocalName)
|| gn.Name.LocalName.ToLower() == pluralizationService.Pluralize(gn.Elements().First().Name.LocalName).ToLower());
var items = isCollection ? gn.Elements().ToList() : new List<XElement>() { gn };
var values = new List<dynamic>();
items.AsParallel().ForAll(i => values.Add((i.HasElements) ? GetAnonymousType(null, i) : i.Value.Trim()));
result[gn.Name.LocalName] = isCollection ? values : values.FirstOrDefault();
});
return result;
}
}
}

Indexing in Elasticsearch

I am having problems indexing in elasticsearch. I have a function which creates an index and another one that creates a type mapping for a json I will be indexing. Both of these work fine but when I try calling the function to index something, it gives me a WebException saying that the remote server returned an error: (503) Server Unavailable. Any help will be greatly appreciated! Thanks!
This is my code:
public static void Main(string[] args)
{
string endpoint = "http://localhost:9200";
string index = "logs";
string type = "activity-log";
createIndex(endpoint, index);
createMapping(endpoint, index, type);
indexEvent(endpoint, index, type);
}
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void createMapping(string endpoint, string index, string type)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/_mapping", endpoint, index, type));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use POST method when creating an index
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
public static void indexEvent(string endpoint, string index, string type)
{
//build the request URL
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/{2}/", endpoint, index, type);
request.ContentType = "application/json"; //set content type of json
request.Method = "POST"; //use POST method when indexing a record without specifying id, and PUT when you specify an id
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
Console.WriteLine("after get response");
Console.ReadLine();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
I was doing something wrong in my createIndex function but here is my working function incase anyone finds it helpful:
public static void createIndex(string endpoint, string index)
{
//Build request url
WebRequest request = WebRequest.Create(string.Format("{0}/{1}/", endpoint, index));
request.ContentType = "application/json"; //set content type of json
request.Method = "PUT"; //use PUT method when creating an index
string json = "{\"settings\":{\"activity-log-events\":{\"number_of_shards\":3,\"number_of_replicas\":2}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
string result = System.Convert.ToBase64String(byteData);
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteData, 0, byteData.Length);
dataStream.Close();
//create a web response
WebResponse response = request.GetResponse();
StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
Console.WriteLine(sr.ReadToEnd().Trim());
Console.ReadKey();
response.Close();
}
You have at least one error in your indexEvent() function. You are setting the string jsonEvent but then using an undefined string json when setting up byteData:
string jsonEvent = "{\"id\":\"123546789\",\"parentId\":\"abc123\",\"event\":\"CloseAccount\"}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
You'll note that you are doing this correctly in the other two functions, using the string json in both places. From createIndex:
string json = "{\"settings\":{\"number_of_shards\":3,\"number_of_replicas\":2}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
and from createMapping:
string json = "{\"activitylogevent\":{\"properties\":{\"id\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"parentId\":{\"type\":\"string\",\"index\":\"not_analyzed\"},\"event\":{\"type\":\"string\",\"index\":\"not_analyzed\"}}}}";
byte[] byteData = Encoding.GetEncoding("UTF-8").GetBytes(json);
There may be other things wrong in the code but that's definitely not going to work.
I made a some changes to my createIndex function and it worked. I posted the changes above.

how to Convert string into Json using Newton Json library

sorry for the silly question, but i am stuck converting for example the following result from a method into Json
public string Test(string input) {
return "Name:" + input;
}
to look like this
{"Name":"Mike"}
Update:
Darin fixed first problem now i am using this way but it is not working
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using(JsonWriter jsonWriter = new JsonTextWriter(sw)) {
jsonWriter.Formatting = Formatting.Indented;
jsonWriter.WritePropertyName("Name");
jsonWriter.WriteValue("Mike");
}
I get
'{"Name":{"m_MaxCapacity":2147483647,"Capacity":16,"m_StringValue":"\\"Name\\": \\"Mike\\"","m_currentThread":0}}';
You could use the JavaScriptSerializer class:
public string Test(string input)
{
var serializer = new JavaScriptSerializer();
return serializer.Serialize(new { Name = input });
}
Example usage:
string json = Test("Mike"); // json = {"Name":"Mike"}
UPDATE:
Didn't notice you wanted a solution using the Json.NET library. Here's one:
string json = JsonConvert.SerializeObject(new { Name = input });