2

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?

Greg B
  • 14,597
  • 18
  • 87
  • 141
  • 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 Answers2

1

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.

Greg B
  • 14,597
  • 18
  • 87
  • 141
jameswykes
  • 185
  • 9
  • 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
1

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.

Community
  • 1
  • 1
Greg B
  • 14,597
  • 18
  • 87
  • 141