4

I have a method like this.

using (MemoryStream memoryStream = new MemoryStream())
{
    DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(Message), this.knowTypes);
    dataContractSerializer.WriteObject(memoryStream, message);

    byte[] byteArray = memoryStream.ToArray();
    memoryStream.Close();
    return byteArray;
}

When I convert the byteArray to string the result is like below: {"__type":"Login:#Project.ProjectName.Sockets","Password":"F9AAD6B7CFBD2A756101","Username":"UserName"}

This result is meaningful my server.

However I want to change this code with because of some character issues.

byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message));
return byteArray;

Now I convert byteArray to string the result like: {"Username":"UserName","Password":"F9AAD6B7CFBD2A756101"}

Also I have tried to use JsonSerializerSettings

 settings = new JsonSerializerSettings();
 settings.TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full;
 settings.TypeNameHandling = TypeNameHandling.Objects;

and result is {"$type":"Project.ProjectName.Sockets.Login, ProjectName","Username":"UserName","Password":"F9AAD6B7CFBD2A756101"}

What is the difference between DataContractJsonSerializer and JsonConvert and it is possible to get same result using JsonConvert.

Blast
  • 955
  • 1
  • 17
  • 40
  • Is it a possibility to change both serializing and deserializing end with `Json.NET`? – Yuval Itzchakov Sep 17 '15 at 08:55
  • The format of Json.NET's type hints is hardcoded. See [Format of 'Special Property' ($type) is hardcoded](https://json.codeplex.com/workitem/22429). – dbc Sep 17 '15 at 09:33
  • Possible duplicate? [JSON.Net - Change $type field to another name?](http://stackoverflow.com/questions/9490345/json-net-change-type-field-to-another-name). – dbc Sep 17 '15 at 09:34

1 Answers1

0

Pass the following settings to the DataContractJsonSerializer and you should never get any type information:

DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings()
{
    EmitTypeInformation = EmitTypeInformation.Never
};
poke
  • 369,085
  • 72
  • 557
  • 602
  • 2
    I think the OP does want to emit type information, just in a different structure. – Yuval Itzchakov Sep 17 '15 at 08:58
  • DataContractJsonSerializerSettings is for .Net 4.5 and later versions. Also I've forgot to say that I am using silverlight 5 so I cannot use `DataContractJsonSerializerSettings ` – Blast Sep 18 '15 at 06:49