Error: The type arguments for method 'System.Web.Script.Serialization.JavaScriptSerializer.Deserialize<T>(string)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
string url = null;
public int GetLinkedIn()
{
var jsonString = new System.Net.WebClient().DownloadString("http://www.linkedin.com/countserv/count/share?url=" + url + "&format=json");
var json = new JavaScriptSerializer().Deserialize<dictionary dynamic="" string="">>(jsonString);
var count = Convert.ToInt32(json["count"]);
return count;
}
You can use JavaScriptSerializer class to resolve the Json response
int GetLinkedIn(string url)
{
url = "http://www.linkedin.com/countserv/count/share?url=" + url + "&format=json";
var jsonString = new WebClient().DownloadString(url);
return new JavaScriptSerializer().Deserialize<LinkdInJson>(jsonString).count;
}
And you need to create a class to represent the entity of the Json response
public class LinkdInJson
{
public int count { get; set; }
public string fCnt { get; set; }
public string fCntPlusOne { get; set; }
public string url { get; set; }
}
The type argument to the Deserialize method is wrong, the correct form is
var dic = new JavaScriptSerializer().Deserialize<Dictionary<string, dynamic>>(jsonString);
Related
I need to deserialize a JSON string into a type which is not know at compile time. There are several classes that it can be deserialized into. The name of the class is provided as input into the application and based on that I want to instantiate the class (already done this through reflection):
var type = Type.GetType(className);
var myClassInstance = (IParser)Activator.CreateInstance(type);
...and then use its type as the generic type parameter for JsonConvert.DeserializeObject<typeof(myClassInstance).Name>(jsonString) but that doesn't work.
How can I provide the class to DeserializeObject<>() dynamically?
Instead of using an generic method overload like JsonConvert.DeserializeObject<T>(String) and having to resort to reflection as some comments state, you could simply use the non generic counterpart JsonConvert.DeserializeObject(String, Type), which just takes in a Type instance like you already have!
Implementation
Initialization
var class1s = new Class1() {
ID = 1, Name = "Test", Comment = "This Code is Tested!."
};
var class2s = new Class2() {
xVal1 = 1, XVal2 = 5, xval3 = 10
};
var JSON1 = Newtonsoft.Json.JsonConvert.SerializeObject(class1s);
var JSON2 = Newtonsoft.Json.JsonConvert.SerializeObject(class2s);
Calling Functions
var classname1 = typeof(Class1).FullName;
var type1 = Type.GetType(classname1);
var classname2 = typeof(Class2).FullName;
var type2 = Type.GetType(classname2);
var c = LocalConverter(JSON1, type1);
var c2 = LocalConverter(JSON2, type2);
Class Models
public class Class1 {
public int ID {
get;
set;
}
public string Name {
get;
set;
}
public string Comment {
get;
set;
}
}
public class Class2 {
public int xVal1 {
get;
set;
}
public int XVal2 {
get;
set;
}
public int xval3 {
get;
set;
}
}
Required Method
private object LocalConverter(string o, Type xtype) {
return Newtonsoft.Json.JsonConvert.DeserializeObject(o, xtype);
}
I am trying to deserialize JSON file and want to assign to object ScanResult. var text showing all the values but scanresult showing null some null values. https://gyazo.com/ff2ce386f845394c458a88d43a1f30d8
please suggest if I am missing something.
//MY jSon File SCAN Test 1-1543045410222.json 's code
{
"at": 1543045410222,
"i": 1000,
"s": {
"Sensor1": ["OFF"],
"Sensor2": ["OFF"],
"DataReady1": ["OFF"],
"DataReady2": ["OFF"],
"CV1": [5.0],
"CV2": [6.0]
}
}
//ViewModel Code is as below:
public void ResendScanResult()
{
var ScanActivities = scanActivityManager.GetAll();
foreach (var item in ScanActivities)
{
var scanName = item.ScanName;
var dir = _dataFilePath + scanName + "\\";
var jsonFileName = string.Format("{0}{1}-{2}.json", dir, scanName, item.ScanDateEpoch);
string fileName = Path.GetFileName(jsonFileName);
// ScanResult scanResult = new ScanResult();
var text = File.ReadAllText(jsonFileName);
//var scanResults = JsonConvert.DeserializeObject<ScanResult>(text);
Common.Model.ScanResult scanResult = JsonConvert.DeserializeObject<Common.Model.ScanResult>(text);
var Mvm = MonitorViewModel.Instance;
// TargetProvider target = Mvm.GetTargetProvider(scanResult);
// Mvm.PublishToServer(target, scanResult);
}
}
and my scanRescult class code is as below :
namespace ABX.Common.Model
{
public class ScanResult
{
public ScanResult()
{
At = DateTimeOffset.Now.ToUnixTimeMilliseconds();
Interval = 1;
}
public string Name { get; set; }
public long At { get; set; }
public long Interval { get; set; }
public JObject Values { get; set; }
public string FileName { get; set; }
public JObject ToJson()
{
JObject json = new JObject
{
{ "at", At },
{ "i", Interval },
{ "s", Values }
};
return json;
}
Either rename your class properties to match your JSON, rename your JSON to match your class properties, or implement a custom JsonConverter, where you can implement arbitrary mapping.
How i cab write a json format in C# string:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string strNJson = #"{to:'topics/extrafx',notification:{title:{0},text:{1},sound: 'default'}}";
strNJson = string.Format(strNJson, not_title, not_body);
streamWriter.Write(strNJson);
streamWriter.Flush();
}
Please advice?
Json is the text serialisation of an object. So you simply have to create an object with those property and serialise it. To assit in creating the class that represent your object you can simply paste a Valid Json to Json 2 C#.
public class Notification
{
public string title { get; set; }
public string text { get; set; }
public string sound { get; set; }
}
public class RootObject
{
public string to { get; set; }
public Notification notification { get; set; }
}
And use it like :
var item = new RootObject {
to = "topics/extrafx",
notification = new Notification {
title = variableFoo,
text = variableBar,
sound = "default"
}
};
var result = JsonConvert.SerializeObject(item);
Try this version:
string not_title, not_body;
not_title = "title";
not_body = "body";
string strNJson = #"{{'to':'topics/extrafx','notification':{{'title':'{0}','text':'{1}','sound': 'default'}}}}";
strNJson = string.Format(strNJson, not_title, not_body);
private const string DATA = #"{
""uuid"": ""27c0f81c-23bc-4878-a6a5-49da58cd30dr"",
""status"": ""Work"",
""job_address"": ""Somewhere"",
""job_description"": ""Just a Test API CALL, John Mckinley's Job""}";
"" Calling the Data to this one
content = new StringContent(DATA, Encoding.UTF8, "application/json");
You can try this.
I have a problem with reading and deserializing the HTTP response from my simple web API that supposes to return IEnumerable of ContactDto object. In contentReader.Read() line I'm getting an error as:
"Data at the root level is invalid. Line 1, position 1."
Controller get code:
[HttpGet]
// GET api/<controller>
public IEnumerable<ContactDto> Get()
{
return new List<ContactDto>()
{
new ContactDto()
{
DateOfBirth = DateTime.Today,
FirstName = "tmp",
LastName = "tmp"
}
};
}
Model code:
public class ContactDto
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
}
Reading and parsing with HttpClient:
public IEnumerable<ContactDto> Read()
{
var serializer = new XmlSerializer(typeof(ContactDto));
var client =new HttpClient();
var stream = client.GetStreamAsync(_feedUrl).Result;
using (var streamReader = new StreamReader(stream))
{
using (var contentReader = new XmlTextReader(streamReader))
{
while (contentReader.Read())
{
var innerEventXml = contentReader.ReadAsString();
using (var stringReader = new StringReader(innerEventXml))
{
yield return (ContactDto) serializer.Deserialize(stringReader);
}
}
}
}
}
Returning a list of objects in your Get action results in a JSON result when calling it, not a XML result.
You can deserialize it using Newtonsoft.Json for example:
string result = client.GetStringAsync().Result;
return JsonConvert.Deserialize<List<ContactDto>>(result);
Althought I would suggest you to use await for the async methods.
This must be trivial but I can't seem to get it done. Given the following data contract class:
public class SampleItem
{
public int Id { get; set; }
public string StringValue { get; set; }
}
when deserialized to JSON by my WCF service, provides the following output:
[{"Id":1,"StringValue":"Hello"}]
Is there any way to include the class name too? i.e.:
"SampleItem": [{"Id":1,"StringValue":"Hello"}]
You could try something like this:
private dynamic AddClassName(SampleItem item)
{
return new {SampleItem = item};
}
And
var item = new SampleItem {Id = 1, StringValue = "Hello"};
dynamic itemClassName = AppendClassName(item);
string json = new JavaScriptSerializer().Serialize(itemClassName);
Debug.WriteLine(json);
Edit - this works for all types:
private static string GetJsonWrapper<T>(T item)
{
string typeName = typeof(T).Name;
string jsonOriginal = new JavaScriptSerializer().Serialize(item);
return string.Format("{{\"{0}\":{1}}}", typeName, jsonOriginal);
}