JavaScriptSerializer.Deserialize array - c#

I'm having trouble deserializing an array in .NET MVC3, any help would be appreciated.
Here's the code snippet:
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
result = (BigCommerceOrderProducts)jsSerializer.Deserialize<BigCommerceOrderProducts>(jsonData);
}
Here's the subset of the data string returned by JSON as jsonData. I've remove extra fields.
"[
{\"id\":33,\"order_id\":230025,...},
{\"id\":34,\"order_id\":230025,...}
]"
Here are the objects:
[Serializable]
public class BigCommerceOrderProducts {
public List<BigCommerceOrderProduct> Data { get; set; }
}
[Serializable]
public class BigCommerceOrderProduct {
public int Id { get; set; }
public int Order_id { get; set; }
...
}
I'm getting this error:
"Type 'Pxo.Models.BigCommerce.BigCommerceOrderProducts' is not supported for deserialization of an array.
Any ideas?

You should deserialize your json string to type List<BigCommerceOrderProduct>. No need for BigCommerceOrderProducts class
var myobj = jsSerializer.Deserialize<List<BigCommerceOrderProduct>>(jsonData);

This little proggy works fine for me. Could be something unexpected in the response stream.
The json output is: {"Data":[{"Id":33,"Order_id":230025},{"Id":34,"Order_id":230025}]}
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
BigCommerceOrderProducts a = new BigCommerceOrderProducts();
a.Data = new List<BigCommerceOrderProduct>();
BigCommerceOrderProduct b = new BigCommerceOrderProduct();
b.Id = 33;
b.Order_id = 230025;
a.Data.Add(b);
b = new BigCommerceOrderProduct();
b.Id = 34;
b.Order_id = 230025;
a.Data.Add(b);
string x = jsSerializer.Serialize(a);
Console.WriteLine(x);
a = jsSerializer.Deserialize<BigCommerceOrderProducts>(x);
Console.WriteLine(a.Data[0].Order_id);
Console.ReadLine();

Related

JSON Not Deserializing

This is one of my first ventures into WCF/JSON. I created a WCF Web Service. This is one of my methods. It is how I serialize the datable to JSON.
public string GetPrayers()
{
DataTable myDt = new DataTable();
myDt = sprocToDT("LoadPrayers");
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
return JSONString;
}
This returns a nice JSON Dataset:
{"GetPrayersResult":"[{\"prayerid\":2,\"prayer\":\"Please pray for my
dog Rusty. He has cancer
:(\",\"prayerCategory\":\"General\",\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayerid\":1,\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerCategory\":\"Sports\",\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]"}
When I go to deserialize it I get all nulls. Here is the classes I created:
public class PrayUpPrayers
{
public string prayer { get; set; }
public string prayerid { get; set; }
public string prayerCategory { get; set; }
public string prayerCategoryID { get; set; }
public string prayerDate { get; set; }
public string handle { get; set; }
public string country { get; set; }
}
public class ThePrayer
{
public PrayUpPrayers prayers { get; set; }
}
}
This is how I am retrieving the JSON:
void getData()
{
var request = HttpWebRequest.Create(string.Format(#"URLGoesHere"));
request.ContentType = "application/json";
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Console.Out.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
string foo = content.ToString();
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
Testing is always null? Is the issue that I am serializing it wrong, could it be the class structure, or is it related to how I am deserializing it. One important note: I checked my JSON on one of these JSONClassesFromC# sites and it only returns the GetPrayersResult as the only class item. Ignoring completely my entire structure.
You didn't provide the code for sprocToDT, but it should create ThePrayer object witch should contain list of PrayUpPrayers
public class ThePrayer
{
public List<PrayUpPrayers> prayers { get; set; }
}
And then you should deserialize ThePrayer object, not PrayUpPrayers.
For example
PrayUpPrayers prayUpPrayers1 = new PrayUpPrayers
{
prayer = "Please pray for my dog Rusty. He has cancer",
prayerid = "2",
prayerCategory = "General",
prayerDate = "2017-06-10T21:24:16.1",
handle = "GuruJee",
country = "USA"
};
PrayUpPrayers prayUpPrayers2 = new PrayUpPrayers
{
prayer = "Help Me I need a appendectomy STAT",
prayerid = "1",
prayerCategory = "Sports",
prayerDate = "2017-04-10T20:30:39.77",
handle = "GuruJee",
country = "USA"
};
ThePrayer thePrayer = new ThePrayer
{
prayers = new List<PrayUpPrayers>
{
prayUpPrayers1, prayUpPrayers2
}
};
myDt in your code should be the same as thePrayer instance in my code.
JSONString = JsonConvert.SerializeObject(myDt, Formatting.None);
will provide Json that looks like
"{\"prayers\":[{\"prayer\":\"Please pray for my dog Rusty. He has
cancer\",\"prayerid\":\"2\",\"prayerCategory\":\"General\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-06-10T21:24:16.1\",\"handle\":\"GuruJee\",\"country\":\"USA\"},{\"prayer\":\"Help
Me I need a appendectomy
STAT\",\"prayerid\":\"1\",\"prayerCategory\":\"Sports\",\"prayerCategoryID\":null,\"prayerDate\":\"2017-04-10T20:30:39.77\",\"handle\":\"GuruJee\",\"country\":\"USA\"}]}"
And deserialize will look like
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.ThePrayer>(foo,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
that's simple. you should deserilze the output twice. try this:
var output= DeserializeObject<string>(foo);
var testing = JsonConvert.DeserializeObject<prayupapp.ModelClasses.PrayUpPrayers>(output,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});

Create a json request object in c#

[{
"channel_id":299,
"requests":[{
"order_id":3975,
"action":"REQUEST_LABELS"
}]
}]
How to create the above request in c# the requests can be multiple.
I am new to c# i tried the below:
Dictionary<long, List<object>> requestObject = new Dictionary<long, List<object>>();
List<object> listrequestObjects = new List<object>();
Request requestOb = new Request();
requestOb.order_id = 2372;
requestOb.action = "REQUEST_LABELS";
listrequestObjects.Add(requestOb);
requestObject.Add(2352635, listrequestObjects);
string requesttest = JsonConvert.SerializeObject(requestObject);
But getting a weird request. Please help.
The structure should look like :
public class Request
{
public int order_id { get; set; }
public string action { get; set; }
}
public class RootObject
{
public int channel_id { get; set; }
public List<Request> requests { get; set; }
}
You need to declare the root object also:
[Serializable]
public class Root {
public int channel_id;
public Request[] requests;
}
Then assign the value and serialize it:
var root = new Root();
root.channel_id = 299;
root.requests = listrequestObjects.ToArray();
string requesttest = JsonConvert.SerializeObject(root);
You can use Newtonsoft.Json.
try this
private JArray GetResponse()
{
var main_array = new JArray();
var channel_id = new JObject();
channel_id.Add("channel_id",299);
var request = new JArray();
var order_id = new JObject();
order_id.Add("order_id",3975);
var action = new JObject();
action.Add("action","REQUEST_LABELS");
request.Add(order_id);
request.Add(action);
main_array.Add(channel_id);
main_array.Add(request);
return main_array;
}
Please try the JavaScriptSerializer class available in namespace
using System.Web.Script.Serialization
JavaScriptSerializer js = new JavaScriptSerializer();
string result = js.Serialize(requestObject);
The requestObject list is your custom class with all necessary properties.
Thanks

deserialize json sting to genric list ( Error converting value to type 'System.Collections.Generic.List`1 Path '', line 1, position 70

here am facing little bit problem while deserializing json string to list
json string : Result of restful service
"\"{\\"UName\\":\\"prasad\\",\\"LastName\\":\\"k\\",\\"FirstName\\":\\"sai\\"}\""
and i want to convert this json string to genric list
my list :
public class _TempUser
{
public string UName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string FirstName
{
get;
set;
}
}
Error is
Error converting value "{"UName":"prasad","LastName":"k","FirstName":"sai"}" to type 'System.Collections.Generic.List`1[loginServices.Login_Service+_TempUser]'. Path '', line 1, position 70.
code : for calling restful service
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http ://IpAddress:Post/Login/RestServiceName.svc/RestMethoName");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json =JsonConvert.SerializeObject(Req);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
List<_TempUser> List = new List<_TempUser>();
List = JsonConvert.DeserializeObject<List<_TempUser>>result
}
}
any modifications or suggestions plz
First your json string must be like this:
"{\"UName\":\"prasad\",\"LastName\":\"k\",\"FirstName\":\"sai\"}"
NOT
"\"{\\"UName\\":\\"prasad\\",\\"LastName\\":\\"k\\",\\"FirstName\\":\\"sai\\"}\""
Then you can parse it using:
string entry = "{\"UName\":\"prasad\",\"LastName\":\"k\",\"FirstName\":\"sai\"}";
var parsedObject = JsonConvert.DeserializeObject<JObject>(entry);
foreach (var dataset in parsedObject.Properties())
{
Console.WriteLine(dataset.Name);
}
I am using Newtonsoft.Json and Newtonsoft.Json.Linq for the parsing.

Issue parsing JSON object response to C# object

I have the following code:
[WebMethod]
public bool AddUser(long warnId, double longitude, double latitude)
{
try
{
string jsonFeature = string.Empty;
jsonFeature += "[{'geometry': {'x': " + longitude + ",'y': " + latitude +
",'spatialReference': {'wkid': 4326}},'attributes': {'UID': '";
jsonFeature += warnId + "','Latitude': '" + latitude + "','Longitude': '" + longitude + "'}}]";
string reqURL = System.Configuration.ConfigurationManager.AppSettings["WARNURL"] + "addFeatures";
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.Headers["Content-type"] = "application/x-www-form-urlencoded";
client.Encoding = System.Text.Encoding.UTF8;
var collection = new System.Collections.Specialized.NameValueCollection();
collection.Add("f", "json");
collection.Add("features", jsonFeature);
byte[] response = client.UploadValues(reqURL, "POST", collection);
MemoryStream stream = new MemoryStream(response);
StreamReader reader = new StreamReader(stream);
string aRespStr = reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
AddResult addResult = jss.Deserialize<AddResult>(aRespStr);
return aRespStr.Contains("true") && aRespStr.Contains("success");
}
}
catch(Exception e)
{
string message = e.Message;
return false;
}
}
when I run it the string aRespStr is:
"{\"addResults\":[{\"objectId\":28,\"globalId\":\"{740490C6-77EE-4AC0-9561-5EBAACE3A0A7}
\",\"success\":true}]}"
I created the following classes to hold the object once I deserialize it:
public class Error
{
public int code { get; set; }
public string description { get; set; }
}
public class AddResult
{
public int objectId { get; set; }
public object globalId { get; set; }
public bool success { get; set; }
public Error error { get; set; }
}
public class RootObject
{
public List<AddResult> addResults { get; set; }
}
but when I run the code the addResult object contains the default object values not the json object values.
The api for this particular response is here:
http://help.arcgis.com/en/arcgisserver/10.0/apis/rest/fsadd.html
any help on getting this to work is greatly appreciated
Try this
RootObject addResults=jss.Deserialize<RootObject>(aRespStr);
or similary you can try this
List<AddResult> addResults = jss.Deserialize<List<AddResult>>(aRespStr);
as you are returning list of AddResult in your json Response.
And Change the content type to application/json
change
client.Headers["Content-type"] = "application/x-www-form-urlencoded";
to
client.Headers["Content-type"] = "Application/json";

Why is my json deserialization failing?

I have the following two objects (which I do not control and can not change):
[Serializable]
[DataContract]
public class AddressContactType : BaseModel
{
public AddressContactType();
[DataMember]
public string AddressContactTypeName { get; set; }
}
[Serializable]
[DataContract]
public abstract class BaseModel
{
protected BaseModel();
[DataMember]
public int Id { get; set; }
[DataMember]
public string NativePMSID { get; set; }
[DataMember]
public string PMCID { get; set; }
}
I am using RestClient to make a GET call to retrieve this data in JSON. The request succeeds. The returned JSON is:
[{"Id":0,"NativePMSID":"1","PMCID":"1020","AddressContactTypeName":"Home"},{"Id":0,"NativePMSID":"2","PMCID":"1020","AddressContactTypeName":"Apartment"},{"Id":0,"NativePMSID":"3","PMCID":"1020","AddressContactTypeName":"Vacation"},{"Id":0,"NativePMSID":"3","PMCID":"1020","AddressContactTypeName":"Other"}]
From that point I attempt to deserialize the data in three different ways.
My code:
var request = new RestRequest("AddressContactType", Method.GET);
request.AddHeader("Accept", "application/json");
request.AddParameter("PMCID", "1020");
#region JSON Deserialization
// ---- Attempt #1
var response = client.Execute<AddressContactType>(request);
// ---- Attempt #2
var myResults = response.Content;
var ms = new MemoryStream(Encoding.UTF8.GetBytes(myResults));
var ser = new DataContractJsonSerializer(typeof(AddressContactType));
var result = (AddressContactType)ser.ReadObject(ms);
// ---- Attempt #3
var jsonSettings = new JsonSerializerSettings()
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.MicrosoftDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
PreserveReferencesHandling = PreserveReferencesHandling.Objects
};
var result2 = new AddressContactType();
result2 = JsonConvert.DeserializeObject<AddressContactType>(new StreamReader(ms).ReadToEnd(), jsonSettings);
#endregion
Under attempt 1, the RestClient attempt returns the error: "Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'."
Under attempt 2, the object result is shown with the correct properties (Id, NativePMSID, PMCID and AddressContactTypeName) but they are all null and only one instance of each is shown.
Attempt 3 just returns a null value for result2.
Any suggestions?
Thanks.
It appears the solution to my problem is:
List<AddressContactType> myResults2;
using (Stream ms2 = new MemoryStream(Encoding.UTF8.GetBytes(myResults)))
{
myResults2 = JsonConvert.DeserializeObject<List<AddressContactType>>(new StreamReader(ms2).ReadToEnd());
}
I was close with one of the previous steps, but this gave me a complete list.

Categories