0

Sorry, but I'm at a loss. This process seems so simplistic to me, but no matter what I do currently I get a new object back with null and zero values. No errors are thrown. I have tried several different processes for converting JSON to a class object, but nothing has worked. Below is the process I'd like to use. Any help as to why this isn't working, would be greatly appreciated.

Please note: What I have to work with uses Hungarian notation. I personally hate it.

//Incoming JSON string to convert:
/*
{"MapPolicySnapshot":{"strMapPolicyID":"189931809","lngLayerTypeID":0,"lngSnapShotID":0,"intZoomLevel":11,"strLayers":",Co    unty,HighRisk,Section,CLU,Policy,Draw","strDateChanged":"","strExtent":"-11405656.02395,5258291.144358,-11353411.315124,5282215.934208"}}
*/

[Serializable]
[DataContract(Name = "MapPolicySnapshot")]
public class PolicySnapshot
{
    [DataMember(Name = "strMapPolicyID")]
    public string strMapPolicyID { get; set; }
    [DataMember(Name = "lngLayerTypeID")]
    public long lngLayerTypeID { get; set; }
    [DataMember(Name = "lngSnapshotID")]
    public int lngSnapShotID { get; set; }  //Not a typo. Former developer.
    [DataMember(Name = "intZoomLevel")]
    public int intZoomLevel { get; set; }
    [DataMember(Name = "strLayers")]
    public string strLayers { get; set; }
    [DataMember(Name = "strDateChanged")]
    public string strDateChanged { get; set; }
    [DataMember(Name = "strExtent")]
    public string strExtent { get; set; }
}

public class AController
{
    //All other code removed, and no, not the actual controller name

    private PolicySnapshot ConvertJSON(string snap)
    {
        // returns null and zeros
        //var snapShot = new JavaScriptSerializer().Deserialize<PolicySnapshot>(snap);

        var snapshot = DeserializeJSON<PolicySnapshot>(snap);
        return snapshot;
    }

    private T DeserializeJSON<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        var ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        var serializer = new DataContractJsonSerializer(obj.GetType());
        obj = (T)serializer.ReadObject(ms);
        ms.Close();
        return obj;
    }
}

When I create a new instance of the PolicySnapshot class with the values from the JSON string, then serialize, I get

{"strMapPolicyID":"189931809","lngLayerTypeID":0,"lngSnapShotID":0,"intZoomLevel":11,"strLayers":",County,HighRisk,Section,CLU,Policy,Draw","strDateChanged":"","strExtent":"-11405656.02395,5258291.144358,-11353411.315124,5282215.934208"}

which is the same data, minus the class name.

Robert H
  • 11,520
  • 18
  • 68
  • 110
Jonathan Hansen
  • 423
  • 1
  • 7
  • 14
  • 1
    Don't use Hungarian notation. It's bad practice generally, and totally unexpected when working with JSON. – Panagiotis Kanavos Mar 18 '14 at 16:37
  • I think the JavaScriptSerializer doesn't pay attention to data contracts. You might want to try DataContractJsonSerializer. See http://stackoverflow.com/a/9403679/521 – palmsey Mar 18 '14 at 16:38
  • Try serializing an object with the same data, and compare the strings. That should point your error out. – BradleyDotNET Mar 18 '14 at 16:39
  • try passing just `{"strMapPolicyID":"189931809","lngLayerTypeID":0,"lngSnapShotID":0,"intZoomLevel":11,"strLayers":",Co unty,HighRisk,Section,CLU,Policy,Draw","strDateChanged":"","strExtent":"-11405656.02395,5258291.144358,-11353411.315124,5282215.934208"}` and see if it works. – user3241191 Mar 18 '14 at 16:44
  • I personally don't ever use Hungarian notation. It is just part of what I'm forced to work with. – Jonathan Hansen Mar 18 '14 at 16:47
  • I will give the DataContractJsonSerializer a shot. Thanks! If that doesn't work, I'll attempt serializing in the reverse, then comparing the strings. Thanks everybody. – Jonathan Hansen Mar 18 '14 at 16:48
  • There is nothing wrong with Hungarian notation, at least when its used properly. It used to be very prevalent at Microsoft, for instance. I still use it today for control names (but not for variable naming), such as "txtFirstName", but not "strFirstName". See Simonyi's original article: http://msdn.microsoft.com/en-us/library/aa260976(v=vs.60).aspx. JSON doesn't care if names are in Hungarian Notation, or, for that matter, if they're in Hungarian. – Cyberherbalist Mar 18 '14 at 17:00
  • @user3241191 passing in the json without the preceding MapPolicySnapshot does indeed result in proper deserialization. This let me to wonder why I have a class name in my JSON text, and I immediately noticed why, which was by my mistake. Both methods now deserialize. Thanks a for the suggestion! – Jonathan Hansen Mar 18 '14 at 17:47

2 Answers2

1

Personally I use RESTsharp as I find it makes serialization/deserialization pretty straight forward.

For instance I can deserialize an object with

orderInfo = JsonConvert.DeserializeObject<OrderStatusInfo>(responseString);

Taking your class and converting it to RESTsharp would look similar to yours, with some small alterations:

public class MapPolicySnapshot
{
    [JsonProperty("strMapPolicyID")]
    public long PolicyID { get; set; }

    [JsonProperty("lngLayerTypeID")]
    public long LayerTypeID { get; set; }

    [JsonProperty("lngSnapshotID")]
    public int SnapShotID { get; set; }

    [JsonProperty("intZoomLevel")]
    public int ZoomLevel { get; set; }

    [JsonProperty("strLayers")]
    public string Layers { get; set; }

    [JsonProperty("strDateChanged")]
    public string DateChanged { get; set; }

    [JsonProperty("strExtent")]
    public string Extent { get; set; }
}

and then doing something like:

MapPolicySnapshop snap = JsonConvert.DeserializeObject<MapPolicySnapshot>(responseString);
Robert H
  • 11,520
  • 18
  • 68
  • 110
  • I'd like to move to something like this, but I was told 'no' to additional open source solutions at this time. I'll keep this in mind for future projects though. – Jonathan Hansen Mar 18 '14 at 17:56
0

You can try something like this:

    private object getClassFromJSon<T>(string JSon)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        return js.Deserialize<T>(JSon);
    }

and call it like this

var variableName = (MyClass)getClassFromJSon<MyClass>(JsonStringHere);
Jayme
  • 1,776
  • 10
  • 28