2ndlife
2ndlife

Reputation: 1376

How to serialize dynamic field names using JSON parser

I am using JSON.Net to serialize my objects. For eg, if this is my object

Class MainData
{
   [JsonProperty("keyValues")]
   string val;
}

the data for 'val' is a key value pair string like this key1:value1. I have a scenario where I should not get the above 'keyValues' name in my final serialized string and instead get a serialized string which looks like this

{
    "key1":"value1"
}

Currently with my serializer I am getting this, which is not what I need

{
     "keyValues":"key:value1"
}

Can somebody guide me to any documentation/solution to dynamically assign the name of the field instead of using the default variable name/JSONProperty Name defined inside the object?

Thanks a lot in advance.

Upvotes: 0

Views: 637

Answers (1)

John C Scott
John C Scott

Reputation: 146

I've been struggling with this all day, what I've done is used a dictionary object and serialised this however I had an error message that was "cannot serialise dictionary", should have read the whole message, "cannot serialise dictionary when the key is not a string or object" this now works for me and gives me a key/value pair

i have the following objects

public class Meal {
public int mealId;
public int value;
public Meal(int MealId, int Value) {
mealId = MealId;
value = Value;
} }

public class Crew
{

public Meal[] AllocatedMeals {
get {
return new Meal[]{ 
new Meal(1085, 2),
new Meal(1086, 1) }; } }

public int AllocatedMealTotal {
get {
return this.AllocatedMeals.Sum(x => x.value); } }
}

then the following code

Dictionary<string,string> MealsAllocated = crew.AllocatedMeals.ToDictionary(x => x.mealId.ToString(), x => x.value.ToString());

return new JavaScriptSerializer().Serialize(
new {
Allocated = new {
Total = crew.AllocatedMealTotal,
Values = MealsAllocated } )

to get

"Allocated":{"Total":3,"Values":{"1085":"2","1086":"1"}}

Upvotes: 1

Related Questions