0

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.

Naveed Zahoor
  • 13
  • 1
  • 8

1 Answers1

0

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.

Naveed Zahoor
  • 13
  • 1
  • 8
  • You should notice that Mono only started to use Microsoft's reference code to implement `DataContractJsonSerializer` since Mono 4.6 release, https://github.com/mono/mono/blob/mono-4.6.0-branch/mcs/class/referencesource/System.Runtime.Serialization/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs If you upgrade your Mono installation to 4.6.x you should use the class. – Lex Li Jan 24 '17 at 12:54