Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following class

[Serializable]
public class ApiRequestStatus :IEquatable<ApiRequestStatus>
{
    public static readonly ApiRequestStatus Failure =
                                            new ApiRequestStatus("Failure");
    public static readonly ApiRequestStatus Success =
                                            new ApiRequestStatus("Success");

    private string _status;

    private ApiRequestStatus(string status)
    {
        this._status = status;
    }

    public override string ToString()
    {
        return _status;
    }

    public bool Equals(ApiRequestStatus other)
    {
        return this._status == other._status;
    }
}

When this is serialized using the System.Web.Script.Serialization.JavaScriptSerializer I'd like it to serialize as the string "Failure" or "Success".

I've tried implementing a custom JavaScriptConverter but this renders my object as an object with zero or more properties depending on the IDictionary<string, object> I return.

e.g. When I return and empty IDictionary<string, object> my object appear as an empty JavaScript object : { }.

If I return new Dictionary<string, object> { {"_status", status._status}} my object appears as { "_status" : "Success" }.

How can I serialize the object just as the string value of it's _status field?

share|improve this question
    
can't say if it works but you could try with "public static implicit operator string(ApiRequestStatus apiRs) { return apiRs._status }". this should at least enable you to do "string s = apiRequestStatusObj;" and the "s" should then contain the status. (the implicit operator should be in you class) –  Joakim Jan 24 '12 at 11:31
    
@Joakim that hasn't had any effect unfortunately. Cheers –  Greg B Jan 24 '12 at 11:46

2 Answers 2

Add a ToJsonString() method to your class, and control your serialization manually - in this case serialize the _status member directly.

For all other / default behaviour, just serialize this (this can be inherited for tidiness) and return it.

share|improve this answer
    
Unfortunately the ApiRequestStatus object is part of a much larger top-level object which is being serialized using the JavaScriptSerializer so I can't get granular control of each object individually. –  Greg B Jan 24 '12 at 12:15

I fixed this by switching my ApiRequestStatus to an enum and using the Json.NET serializer in conjunction with the JsonConverter attribute but I'd still be interested to see if this is possible with the JavaScriptSerializer.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.