Javascriptserializer.Deserialize - How to Change Field Names

Changing property names for serializing

For Json.NET and DataContractJsonSerializer use DataMemberAttribute:

[DataMember(Name="PropertyB")]
T PropertyA { ... }

Make sure that your class is decorated with the [DataContract] attribute as well.

If you're using JavaScriptSerializer, you need to create derived implementation, as described here:
JavaScriptSerializer.Deserialize - how to change field names

JavaScriptSerializer - custom property name

Answering in several parts:

  1. To make a property named base, you need to prefix the name with an @:

    public int @base { get; set; }
  2. You wrote that you are using JavaScriptSerializer. The attribute [JsonProperty] is for a completely different serializer, Json.NET. This attribute has no effect on JavaScriptSerializer.

    If you were to switch to Json.NET, you would be able to use this attribute.

    Or, if you were to instead apply data contract attributes to your type, you could use either Json.NET or DataContractJsonSerializer to serialize your type with renamed properties.

  3. In fact, JavaScriptSerializer has no way to rename a property for serialization outside of writing a custom JavaScriptConverter. This serializer is quite bare-bones; the only serialization attribute it supports is ScriptIgnore to suppress serialization of a property.

Changing property names for serializing

For Json.NET and DataContractJsonSerializer use DataMemberAttribute:

[DataMember(Name="PropertyB")]
T PropertyA { ... }

Make sure that your class is decorated with the [DataContract] attribute as well.

If you're using JavaScriptSerializer, you need to create derived implementation, as described here:
JavaScriptSerializer.Deserialize - how to change field names

Rename Property from Deserialized Javascript

Looks like you can't do it easily for JavaScriptSerializer, but you can do that in Json.Net or using DataContractSerializer (part of .Net framework).

For Json.Net you can put JsonProperty attribute that specifies a name.

class MyClass
{
[JsonProperty(Name="create_date")]
public string CreateDate {get;set;}
}

And for DataContractSerializer use DataMember attribute

Deserialize the JSON where the values are field names with JSON.NET

You can create a custom JsonConverter which serializes/deserializes Role[]. You can then decorate your Roles property with the JsonConverterAttribute like this:

public class User
{
public string Name { get; set; }
[JsonConverter(typeof(RolesConverter))]
public Role[] Roles { get; set; }
}

In your converter class you are able to read an object and return an array instead. Your converter class may look like this:

class RolesConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Role[]);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
// deserialize as object
var roles = serializer.Deserialize<JObject>(reader);
var result = new List<Role>();

// create an array out of the properties
foreach (JProperty property in roles.Properties())
{
var role = property.Value.ToObject<Role>();
role.Id = int.Parse(property.Name);
result.Add(role);
}

return result.ToArray();
}


public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

JavaScriptSerializer - how to deserialize a property with a dash ( - ) in it's name?

One alternative is to use the DataContractJsonSerializer instead of the JavascriptSerializer.

If you declare your classes like this:

        [DataContract]
private class DeserializationMain
{
[DataMember(Name = "result")]
public string result; //works
[DataMember(Name = "arguments")]
public args arguments; //works, has deserialized activeTorrentCount
[DataContract]
public class args
{
[DataMember(Name = "activeTorrentCount")]
public int activeTorrentCount;

[DataMember(Name = "cumulative-stats")]
public current cumulative_stats; //doesn't work, equals null
[DataContract]
public class current
{
[DataMember(Name = "downloadedBytes")]
public long downloadedBytes;
}
}
}

You can deserialize it like this:

string json = "{\"result\":\"success\"   ,    \"arguments\": {  \"activeTorrentCount\":22,  \"cumulative-stats\": {   \"downloadedBytes\":1111      }       }     }";

DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DeserializationMain));
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DeserializationMain result = serializer.ReadObject(ms) as DeserializationMain;

Console.WriteLine("Cumulative-stats.downloadedBytes: "+result.arguments.cumulative_stats.downloadedBytes);

Will produce:
Cumulative-stats.downloadedBytes: 1111



Related Topics



Leave a reply



Submit