1
{"key":"abc/1"}

I want to store the value in two fields instead of one. I can do the following.

[JsonProperty(PropertyName = "key", Required = Required.Always)]
public string Value { get; set; }

However, I want to have two fields but use JsonPropertyto serialize and deserialize them as a combined string. For example, if I define the following fields:

public string ValueScope { get; set; }
public int ValueId { get; set; }

I want to use JsonProperty or any other tag to populate the fields while deserializing. Is it possible to do that, i.e. populate ValueScope as "abc" and ValueId as 1 ?

1 Answer 1

1

Yes, you can actually implement the get and set of the 2 properties to just manipulate the underlying JsonProperty.

Here's a quick example of how you might go about it (warning: I just wrote this out in notepad, so please excuse any typos).

public string ValueScope
{
    get
    {
        var values = (this.Value ?? "").Split('/');
        if (values.Length == 2)
            return values[0];
        else
            return null;
    }
    set
    {
        this.Value = (value ?? "") + "/" + this.ValueId.ToString();
    }
}

public int ValueId
{
    get
    {
        int currentValue;
        var values = (this.Value ?? "").Split('/');
        if (values.Length == 2 && int.TryParse(values[1], out currentValue))
            return currentValue;
        else
            return default(int);
    }
    set
    {
        this.Value = (this.ValueScope ?? "") + "/" + value.ToString();
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

So you mean I should keep three fields, Value, ValueScope and ValueId, right ? I wanted to do it with two only.
To make it work with only 2 fields, I suppose you'd have to implement your own JsonConverterAttribute out of json.net that has a parameter for the name of the other property, then add JsonIgnore to the other property, but I'm not sure honestly how the deserialization might work for that. Otherwise, you might have to consider your own JsonSerializer which is much more tightly coupled (blog.maskalik.com/asp-net/…).
Also, here's the docs on implementing your own JsonSerializer - newtonsoft.com/json/help/html/CustomJsonConverter.htm
Actually, callbacks might be more helpful in this scenario.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.