简体   繁体   中英

Custom JSON converter not being called after posting data from ajax to controller

I have implemented this custom json converter to convert types depending on the data received, but it seems like it's never being called. Is the action doing the native parsing and my converter is not being used?

My results are posted into this action

[HttpPost]
public JsonResult saveCustomfields(CustomFields customfields)
{

}

Model

public class Field
{
    public string _label { get; set; }
    public string _name { get; set; }
    public string _type { get; set; }
    public List<Option> option { get; set; }
}

public class Fields
{
    [JsonProperty("field")]
    [JsonConverter(typeof(SingleOrArrayConverter<Field>))]
    public List<Field> field { get; set; }
}

public class Formtemplate
{
    [JsonProperty("fields")]
    public Fields fields { get; set; }
}

public class CustomFields
{
    [JsonProperty("formtemplate")]
    public Formtemplate formtemplate { get; set; }
}

Custom converter

public class SingleOrArrayConverter<T> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(List<T>));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        if (token.Type == JTokenType.Array)
        {
            return token.ToObject<List<T>>();
        }
        return new List<T> { token.ToObject<T>() };
    }

    public override bool CanWrite
    {
        get { return false; }
    }

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

Ajax

<script>
    jQuery(document).ready(function ($) {
        var fbTemplate = document.getElementById('fb-template');
        var formBuilder = $(fbTemplate).formBuilder();

        $(".form-builder-save").click(function (e) {
            e.preventDefault();
            var x2js = new X2JS();
            var xml = formBuilder.data('formBuilder').formData;
            var json = x2js.xml_str2json(xml);

            alert(JSON.stringify(json));

            $.ajax({
                url: "saveCustomfields",
                type: "POST",
                data: JSON.stringify(json),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
            });
        });
    });
</script>

Disclaimer: This isn't a direct answer, but an alternative solution

So the reason I saw this a potential solution is because of this C# attribute:

[JsonConverter(typeof(SingleOrArrayConverter<Field>))]
public List<Field> field { get; set; }

I'm reading this as a single item or array converter to a list. So this is really easy in JavaScript.

So there is a nifty little trick with JavaScript using the literal and instanceof

if (!(field instanceof Array)) { // if field isn't an array
   field = [field]; // make it one
} 

This basically says, if the variable ain't an array, then make it one.

This may be easier to do then to get C# to fiddle around with the JSON.

Also in my eyes, i believe you should always be communicating the simplest JSON between client and server (and visa versa).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM