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:
To make a property named
base
, you need to prefix the name with an@
:public int @base { get; set; }
You wrote that you are using
JavaScriptSerializer
. The attribute[JsonProperty]
is for a completely different serializer, Json.NET. This attribute has no effect onJavaScriptSerializer
.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.In fact,
JavaScriptSerializer
has no way to rename a property for serialization outside of writing a customJavaScriptConverter
. This serializer is quite bare-bones; the only serialization attribute it supports isScriptIgnore
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
Change a Web.Config Programmatically with C# (.Net)
Javascriptserializer.Deserialize - How to Change Field Names
Combobox: Adding Text and Value to an Item (No Binding Source)
Does Using "New" on a Struct Allocate It on the Heap or Stack
Password Protect a SQLite Db. Is It Possible
What's the Difference Between Task.Start/Wait and Async/Await
Copy File(S) from One Project to Another Using Post Build Event...Vs2010
How to Move Mouse Cursor Using C#
How Does the C# Compiler Detect Com Types
Making a Property Deserialize But Not Serialize with JSON.Net
How to Call an Async Method from a Getter or Setter
Using Protobuf-Net, I Suddenly Got an Exception About an Unknown Wire-Type
How to Find the Most Recent File in a Directory Using .Net, and Without Looping
How to Format Datetime Columns in Datagridview
The Type Is Defined in an Assembly That Is Not Referenced, How to Find the Cause