Unable to use DataContractJsonSerializer in Xamarin.Mac - json

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.

Related

Make .Net Web API JSON output pretty

I'm using code below to get data in JSON format using Newtonsoft.Json:
my code to create the JSON is
Dim sb As New StringBuilder()
Dim sw As New StringWriter(sb)
Dim writer As JsonWriter = New JsonTextWriter(sw)
writer.WriteStartArray()
For Each elements As JToken In result
If i = 0 Then
i += 1
Continue For
End If
For Each aaa As JToken In elements
writer.WriteStartObject()
Dim pmid = aaa("uid").Value(Of String)
Dim issn = aaa("issn").Value(Of String)
Dim essn = aaa("essn").Value(Of String)
Dim source = aaa("source").Value(Of String)
Dim sortpubdate = aaa("sortpubdate").Value(Of String)
writer.WritePropertyName("pmid")
writer.WriteValue(pmid)
writer.WritePropertyName("journal")
writer.WriteValue(source)
writer.WritePropertyName("issn")
writer.WriteValue(issn)
writer.WritePropertyName("essn")
writer.WriteValue(essn)
writer.WritePropertyName("sortpubdate")
writer.WriteValue(sortpubdate)
writer.WritePropertyName("pubYear")
writer.WriteEndObject()
Next
Next
writer.Close()
Return sb.ToString
and the output code is
public HttpResponseMessage Get()
{
string yourJson = GetJsonFromSomewhere();
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json");
return response;
}
My current output is.
[{"pmid":"29241721","issn":"0749-3797","essn":"1873-2607","journal":"Am J Prev Med","pubYear":"2018","ImpactFactor":" 4.127"},{"pmid":"28987617","issn":"0166-4328","essn":"1872-7549","journal":"Behav Brain Res","pubYear":"2018","ImpactFactor":" 3.173"},
Is there a way I can indent my output?
[{
"pmid": "29241721",
"issn": "0749-3797",
"essn": "1873-2607",
"journal": "Am J Prev Med",
"pubYear": "2018",
"ImpactFactor": " 4.127"
}, {
Is there a way I can do it like below?
this.SerializerSettings.Formatting = Formatting.Indented;
The client side is just a simple browser URL that get a response
You should indent your object in serialization time and then use it everywhere you want. If GetJsonFormatSomewhere() is your serialization method you should seralize your object in that method below:
var serializedObject = JsonConvert.SerializeObject(data, Formatting.Indented);
and then pass indented object to StringContent method.
Note: it's better to indent your output in client side, that way your packet size will stay small and it's performance friendly.
I got what I needed with
Dim writer As JsonWriter = New JsonTextWriter(sw)
writer.Formatting = Newtonsoft.Json.Formatting.Indented

Read DynamicJsonArray with razor (mvc4 Umbraco)

I'm reading Json from https://demoapi.thismoment.com/v4.1/api/content
Reading it as stream:
Stream stream = wc.OpenRead(url);
using (StreamReader reader = new StreamReader(stream))
{
String request = reader.ReadToEnd();
var requestJson = #Json.Decode(request);
and getting list of results
var resultsList = new List<dynamic>(requestJson.results);
When trying to read next level
var resultsList = new List<dynamic>(requestJson.results.media);
I'm getting this error: System.ArgumentNullException: Value cannot be null.
When I iterate through the list
foreach (var item in resultsList)
{
<a>#item.media</a>
}
each media item is System.Web.Helpers.DynamicJsonArray.
I need to read this array, so I can get url and size of each image.
The above json url is public.
I'm doing it in Umbraco 7, which uses razor code (aps mvc 4).
You can use following method to do it:
private static List<T> GetcollectionFromJason<T>(string jasonUrl) where T : new()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(jasonUrl);
List<T> retCollection = new List<T>();
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
if (responseStream != null)
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string jsonString = reader.ReadToEnd();
JavaScriptSerializer serializer = new JavaScriptSerializer();
retCollection = serializer.Deserialize<List<T>>(jsonString);
}
}
}
catch (WebException exp)
{
WebResponse errorResponse = exp.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
if (responseStream != null)
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
}
}
}
return retCollection;
}
And to call it you can have this:
List<YourModel> technicalIssues = GetcollectionFromJason<YourModel>(YourJsonUrl);

WCF, Serialize Json to XML

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);

Using Gson and JsonObject to format and parse data

I am using JsonObject and Gson to format the data i need to send in the form of String and then retrieve and parse it somewhere else.
This is my simple code which is not working:
public static void main(String[] args)
{
Gson g = new Gson();
Gson listG = new Gson();
ArrayList<String> l= new ArrayList<String>();
l.add("abcd");
l.add("efgh");
l.add("ijkl");
String list = listG.toJson(l);
JsonObject jObject = new JsonObject();
jObject.addProperty("command" , 1);
jObject.addProperty("message" , "this is a test message");
jObject.addProperty("list" , list);
String toSend = g.toJson(jObject);
System.out.println(toSend);
Gson rec = new Gson();
JsonObject newObj = rec.fromJson(toSend, JsonObject.class);
System.out.println(newObj); // getting nothing in newObj
}
What am i doing wrong here?
You should use:
JsonObject newObj = new JsonParser().parse(toSend).getAsJsonObject();
Lots of calls in there, but the gist is to use the JsonParser class.

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 });