I have a roadblock where I have to transform a simple User class to a very specific JSON in the form of
{"fields": {
"Name": {
"stringValue": "test"
},
"Password": {
"stringValue": "Password"
},
"email" : {
"stringValue" : "emailexample"
}
}}
where stringValue is the value of the class variable which is enclosed in the name of the variable. So far I've tried to create my own Serializer to fix this but I can only create one field ie
{"Fields": {"email": {"stringValue": "emailexample"}}}
before I get the error of Newtonsoft.Json.JsonException: 'Newtonsoft.Json.Linq.JProperty cannot have multiple values.', So I'm wondering if my way of doing it is even possible (this is my first time trying to create a custom serializer) or if I need to approach this in a completely different direction. What I've tried so far is below.
public override void WriteJson(JsonWriter writer, User value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject) t;
IList<string> values = o.Properties().Select(p => p.Value.ToString()).ToList();
IList<string> names = o.Properties().Select(p => p.Name).ToList();
//o.RemoveAll();
JObject val = new JObject(new JProperty("stringValue", new JValue(values[0])));
JProperty fields = new JProperty(names[0], val);
JObject field = new JObject(fields);
JProperty test = new JProperty("Fields", field);
for (int i=1; i<names.Count;i++)
{
val = new JObject(new JProperty("stringValue", new JValue(values[i])));
JProperty name = new JProperty(names[i], val);
JObject jObject = new JObject(name);
test.Add(jObject);
}
o.WriteTo(writer);
}
}