I have following method, which is read JSON from the directory and de-serialize the JSON into C# class object.
public static JObject readJson(string fileName)
{
string JSON = "";
List<string> keyList = new List<string>();
using (StreamReader r = new StreamReader(fileName))
{
JSON = r.ReadToEnd();
}
JObject parsed = JObject.Parse(JSON);
var name = parsed["2"];
Numbers deserializedClass = JsonConvert.DeserializeObject<Numbers>(name.ToString());
return parsed;
}
Here you can see, I'm used class called Numbers. I'm passing separate JSON file's name to the above method, based on that I also need to pass Class to convert JSON into C# object. How can I pass class to the above method as a generic? then I think I can modify this line,
var deserializedClass = JsonConvert.DeserializeObject<AnyClass>(name.ToString());
is it possible to do?
try this:
public static JObject readJson<T>(string fileName)
{
string JSON = "";
List<string> keyList = new List<string>();
using (StreamReader r = new StreamReader(fileName))
{
JSON = r.ReadToEnd();
}
JObject parsed = JObject.Parse(JSON);
var name = parsed["2"];
Numbers deserializedClass = JsonConvert.DeserializeObject<T>(name.ToString());
return parsed;
}
https://learn.microsoft.com/en-us/dotnet/standard/generics/
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics
This method uses Generics and will take the Type you specify and return the object of that type.
public static T readJson<T>(string fileName)
{
var JSON = string.Empty;
using (var r = new StreamReader(fileName))
{
JSON = r.ReadToEnd();
}
var parsed = JObject.Parse(JSON);
var name = parsed["2"];
var deserializedClass = JsonConvert.DeserializeObject<T>(name.ToString());
return deserializedClass;
}
Usage:
var resultObject = readJson<Number>(fileName);
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/generics
How to read it using Newtonsoft.Json?
{
"192.168.0.12":
{
"Name":"12",
"Mode":"STOP"
},
"192.168.0.13":
{
"Name":"13",
"Mode":"STOP"
}
}
I am using this data class as below:
class Device{
public string Name;
public string Mode;
}
Dictionary<string, Device> devices;
So, I tried this code to deserialize. But, I can't read value from JToken as dictionary.
JObject JDevices = JObject.Parse(Encoding.ASCII.GetString(buffer));
foreach (JProperty property in JDevices.Properties())
{
string name = property.Name;
JToken value = property.Value;
// to read Device.Name and Device.Mode
}
You can use dynamic object var result = JsonConvert.DeserializeObject<dynamic>(json);
Code to convert to Dictionary:
Dictionary<string, Device> devices = new Dictionary<string, Device>();
string json = "{\"192.168.0.12\": {\"Name\":\"12\",\"Mode\":\"STOP\"},\"192.168.0.13\": {\"Name\":\"13\",\"Mode\":\"STOP\"}}";
var result = JsonConvert.DeserializeObject<dynamic>(json);
foreach (var item in result)
{
var name = item.Name;
evices.Add(item.Name.ToString(), new Device {Name = item.Value.Name.ToString(), Mode = item.Value.Mode.ToString()});
}
Try this, no need to use dynamic.
var json = "{
"192.168.0.12":
{
"Name":"12",
"Mode":"STOP"
},
"192.168.0.13":
{
"Name":"13",
"Mode":"STOP"
}
}";
var result = JsonConvert.DeserializeObject<Dictionary<string, Device>>(json);
foreach (var device in result.Values)
{
var name = device.Name;
var mode = device.Mode;
}
I am really not sure if this could be achievable, How can i remove some nested keys in an Object and make the object very flat. I have a dynamic object as follows,
EventData": { "ChangeSet": { "Change": {
"changes": [
] } } }
and i want to change the above to
EventData": { [] }
is this can be achieved in C#?
Use the NewtonSoft.JSon package.. Following code does the trick. I made it a string array because I do not know what you need but you can change this to your liking.
const string complex = "{\"EventData\": { \"ChangeSet\": { \"Change\": { \"changes\" : [ ]}}}}";
Call to method:
string simple = returnSimpleObject(complex);
public class SerializeData
{
public string[] EventData { get; set; }
}
private static string returnSimpleObject(string Json)
{
JObject jobject = JObject.Parse(Json);
JToken tEventData = jobject.SelectToken("EventData");
SerializeData myEvent = tEventData.ToObject<SerializeData>();
JToken tchanges = jobject.SelectToken("EventData.ChangeSet.Change.changes");
myEvent.EventData = tchanges.ToObject<string[]>();
JsonSerializer serializer = new JsonSerializer();
StringWriter strWrite = new StringWriter();
JsonWriter myWriter = new JsonTextWriter(strWrite);
serializer.Serialize(myWriter, myEvent);
return strWrite.ToString();
}
I am trying to parse the result from the google speech to text API. The json response is :
{"result":[]}
{"result":[
{"alternative":[
{"transcript":"hello Google how are you feeling","confidence":0.96274596},
{"transcript":"hello Google how are you today","confidence":0.97388196},
{"transcript":"hello Google how are you picking","confidence":0.97388196},
{"transcript":"hello Google how are you kidding","confidence":0.97388196}
]
,"final":true}]
,"result_index":0
}
Now i am trying to parse it through JObject. The problem is occurring in parsing the Result object which is appearing twice so, how do i parse the second Result object. Here is my code which i am trying is :
StreamReader SR_Response = new StreamReader(HWR_Response.GetResponseStream());
Console.WriteLine(SR_Response.ReadToEnd()+SR_Response.ToString());
String json_response = SR_Response.ReadToEnd() + SR_Response.ToString();
JObject joo = JObject.Parse(json_response);
JArray ja = (JArray)joo["result"];
foreach (JObject o in ja)
{
JArray ja2 = (JArray)o["alternative"];
foreach (JObject h in ja2)
{
Console.WriteLine(h["transcript"]);
}
}
Next solution i tried using deserialize object code is:
string responseFromServer = (SR_Response.ReadToEnd());
String[] jsons = responseFromServer.Split('\n');
String text = "";
foreach (String j in jsons)
{
dynamic jsonObject = JsonConvert.DeserializeObject(j);
if (jsonObject == null || jsonObject.result.Count <= 0)
{
continue;
}
Console.WriteLine((string)jsonObject["result"]["alternative"][0]["transcript"]);
text = jsonObject.result[0].alternative[0].transcript;
}
Console.WriteLine("MESSAGE : "+text);
What you have is a series of JSON root objects concatenated together into a single stream. As explained in Read Multiple Fragments With JsonReader such a stream can be deserialized by setting JsonReader.SupportMultipleContent = true. Thus, to deserialize your stream, you should first introduce the following extension methods:
public static class JsonExtensions
{
public static IEnumerable<T> DeserializeObjects<T>(Stream stream, JsonSerializerSettings settings = null)
{
var reader = new StreamReader(stream); // Caller should dispose
return DeserializeObjects<T>(reader, settings);
}
public static IEnumerable<T> DeserializeObjects<T>(TextReader textReader, JsonSerializerSettings settings = null)
{
var ser = JsonSerializer.CreateDefault(settings);
var reader = new JsonTextReader(textReader); // Caller should dispose
reader.SupportMultipleContent = true;
while (reader.Read())
{
if (reader.TokenType == JsonToken.None || reader.TokenType == JsonToken.Undefined || reader.TokenType == JsonToken.Comment)
continue;
yield return ser.Deserialize<T>(reader);
}
}
}
Next, using a code-generation utility such as http://json2csharp.com/, generate c# classes for a single JSON root object, like so:
public class Alternative
{
public string transcript { get; set; }
public double confidence { get; set; }
}
public class Result
{
public List<Alternative> alternative { get; set; }
public bool final { get; set; }
}
public class RootObject
{
public List<Result> result { get; set; }
public int result_index { get; set; }
}
And deserialize as follows:
List<RootObject> results;
using (var stream = HWR_Response.GetResonseStream())
{
results = JsonExtensions.DeserializeObjects<RootObject>(stream).ToList();
}
Having done this you can use standard c# programming techniques such as Linq to enumerate the transcript values, such as:
var transcripts = results
.SelectMany(r => r.result)
.SelectMany(r => r.alternative)
.Select(a => a.transcript)
.ToList();
If you don't want define a fixed data model for your JSON collection, you can deserialize directly to a list of JObject like so:
List<JObject> objs;
using (var stream = HWR_Response.GetResonseStream())
{
objs = JsonExtensions.DeserializeObjects<JObject>(stream).ToList();
}
Then you can use SelectTokens() to select the values of all the "transcript" properties nested inside each object:
var transcripts = objs
// The following uses the JSONPath recursive descent operator ".." to pick out all properties named "transcript".
.SelectMany(o => o.SelectTokens("..transcript"))
.Select(t => t.ToString())
.ToList();
Updated sample fiddle showing both options.
I'm trying to deserialize a Facebook friend's Graph API call into a list of objects. The JSON object looks like:
{"data":[{"id":"518523721","name":"ftyft"},
{"id":"527032438","name":"ftyftyf"},
{"id":"527572047","name":"ftgft"},
{"id":"531141884","name":"ftftft"},
{"id":"532652067","name"...
List<EFacebook> facebooks = new JavaScriptSerializer().Deserialize<List<EFacebook>>(result);
It's not working, because the primitive object is invalid. How can I deserialize this?
You need to create a structure like this:
public class Friends
{
public List<FacebookFriend> data {get; set;}
}
public class FacebookFriend
{
public string id {get; set;}
public string name {get; set;}
}
Then you should be able to do:
Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
The names of my classes are just an example. You should use proper names.
Adding a sample test:
string json =
#"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);
foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}
Produces:
id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft
Sometimes I prefer dynamic objects:
public JsonResult GetJson()
{
string res;
WebClient client = new WebClient();
// Download string
string value = client.DownloadString("https://api.instagram.com/v1/users/000000000/media/recent/?client_id=clientId");
// Write values
res = value;
dynamic dyn = JsonConvert.DeserializeObject(res);
var lstInstagramObjects = new List<InstagramModel>();
foreach(var obj in dyn.data)
{
lstInstagramObjects.Add(new InstagramModel()
{
Link = (obj.link != null) ? obj.link.ToString() : "",
VideoUrl = (obj.videos != null) ? obj.videos.standard_resolution.url.ToString() : "",
CommentsCount = int.Parse(obj.comments.count.ToString()),
LikesCount = int.Parse(obj.likes.count.ToString()),
CreatedTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds((double.Parse(obj.created_time.ToString()))),
ImageUrl = (obj.images != null) ? obj.images.standard_resolution.url.ToString() : "",
User = new InstagramModel.UserAccount()
{
username = obj.user.username,
website = obj.user.website,
profile_picture = obj.user.profile_picture,
full_name = obj.user.full_name,
bio = obj.user.bio,
id = obj.user.id
}
});
}
return Json(lstInstagramObjects, JsonRequestBehavior.AllowGet);
}
A great way to automatically generate these classes for you is to copy your JSON output and throw it in here:
http://json2csharp.com/
It will provide you with a starting point to touch up your classes for deserialization.
Very easily we can parse JSON content with the help of dictionary and JavaScriptSerializer. Here is the sample code by which I parse JSON content from an ashx file.
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
string _Name = sData["Name"].ToString();
string _Subject = sData["Subject"].ToString();
string _Email = sData["Email"].ToString();
string _Details = sData["Details"].ToString();
Newtonsoft.JSON is a good solution for these kind of situations. Also Newtonsof.JSON is faster than others, such as JavaScriptSerializer, DataContractJsonSerializer.
In this sample, you can the following:
var jsonData = JObject.Parse("your JSON data here");
Then you can cast jsonData to JArray, and you can use a for loop to get data at each iteration.
Also, I want to add something:
for (int i = 0; (JArray)jsonData["data"].Count; i++)
{
var data = jsonData[i - 1];
}
Working with dynamic object and using Newtonsoft serialize is a good choice.
I agree with Icarus (would have commented if I could),
but instead of using a CustomObject class,
I would use a Dictionary (in case Facebook adds something).
private class MyFacebookClass
{
public IList<IDictionary<string, string>> data { get; set; }
}
or
private class MyFacebookClass
{
public IList<IDictionary<string, object>> data { get; set; }
}
Serialization:
// Convert an object to JSON string format
string jsonData = JsonConvert.SerializeObject(obj);
Response.Write(jsonData);
Deserialization::
To deserialize a dynamic object
string json = #"{
'Name': 'name',
'Description': 'des'
}";
var res = JsonConvert.DeserializeObject< dynamic>(json);
Response.Write(res.Name);
If you're using .NET Core 3.0, you can use System.Text.Json (which is now built-in) to deserialize JSON.
The first step is to create classes to model the JSON. There are many tools which can help with this, and some of the answers here list them.
Some options are http://json2csharp.com, http://app.quicktype.io, or use Visual Studio (menu Edit → Paste Special → Paste JSON as classes).
public class Person
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Response
{
public List<Person> Data { get; set; }
}
Then you can deserialize using:
var people = JsonSerializer.Deserialize<Response>(json);
If you need to add settings, such as camelCase handling, then pass serializer settings into the deserializer like this:
var options = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
var person = JsonSerializer.Deserialize<Response>(json, options);
You can use this extensions
public static class JsonExtensions
{
public static T ToObject<T>(this string jsonText)
{
return JsonConvert.DeserializeObject<T>(jsonText);
}
public static string ToJson<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
}
Here is another site that will help you with all the code you need as long as you have a correctly formated JSON string available:
https://app.quicktype.io/