1

now I have some data as below:

{"parameters":{"fields":["a","b","c"]}

and I use ajax to send the request to .net WebMethod like below:

$.ajax({
    url: 'Query/Query.asmx/test2?nocache=1',
                    dataType: "json",
                    data: JSON.stringify(data),
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",

})

and the WebMethod I used in query.asmx is:

[WebMethod]
public string test2(Dictionary<string, object> parameters)
{
    return "ok";
}

we can see that the parameters["fields"] is of type System.Object[]

But now I have a requirement to compress the data and decompress it in backend, and the data becomes a string(after decompressed). Now I want to deserialize it to exact the same type as before.

after decompression, the data becomes a JSON string:

"{\"parameters\":{\"fields\":[\"a\",\"b\",\"c\"]}}"

Now I want to use JavaScriptSerializer to deserialize it to the same type. But What I can get is parameters["fields"] of type System.Collections.ArrayList and not the type System.Object[] I require.

the code is like below

public class TestDataObject
{
    public Dictionary<string, object> parameters { get; set; }
}

-

var serializer = new JavaScriptSerializer();
var a = serializer.Deserialize<TestDataObject>(d);

So the question is: is there a way for me to deserialize it to exactly the same type? I can't use another library since I have got some javascriptSerializer converters implemented for some customized types.

2 Answers 2

1

You can change type of value in dictionary to object[] instead of object:

public class TestDataObject
{
    public Dictionary<string, object[]> parameters { get; set; }
}

string json = "{\"parameters\":{\"fields\":[\"a\",\"b\",\"c\"]}}";
var serializer = new JavaScriptSerializer();
var a = serializer.Deserialize<TestDataObject>(json);
a.parameters["fields"].GetType() == typeof(object[]); //equals True
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for your answer. but in the real case, it has more than one level, I just can't give all nested elements types. sorry I didn't make it clear
and in 'parameters' there are more than this array-like type. It has some other primitive types and nested object.
1

In JavascriptSerializer, there is a method ConvertToType which can be used to convert an object to a class instance. After DeserializeObject() is called, the result type is exactly what I want. So, the code can be:

    var b = serializer.DeserializeObject(d);
    var c = serializer.ConvertToType(b, typeof(TestDataObject));

Comments

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.