How to Deserialize JSON data?
You can deserialize this really easily. The data's structure in C# is just List<string[]>
so you could just do;
List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString);
The above code is assuming you're using json.NET.
EDIT: Note the json is technically an array of string arrays. I prefer to use List<string[]>
for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][]
but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.
How to deserialize Json to an object?
var s = "{\r\n \"Status\": \"PLANNED\"\r\n}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<StatusModel>(s);
The model you have defined is incorrect.
Your model should be like this:
public class StatusModel
{
public string Status { get; set; }
}
Now value will be extracted to this model and you can access the value like:
var value = obj.Status; //"PLANNED"
How to deserialize JSON list to C# List of objects
your json
json= "\"[{\\\"Id\\\":19162,\\\"LotId\\\":21243,\\\"LotNumber\\\":\\\"H6469\\\",\\\"LotType\\\":20,\\\"ConfirmationStatus\\\":0,\\\"Date\\\":\\\"2016-02-17T10:51:06.757\\\"},{\\\"Id\\\":19163,\\\"LotId\\\":21244,\\\"LotNumber\\\":\\\"H6469a\\\",\\\"LotType\\\":20,\\\"ConfirmationStatus\\\":0,\\\"Date\\\":\\\"2016-02-17T10:51:19.933\\\"}]\"";
your json was serialized twice (probably by using JSON.stringify) and needs to be fixed at first
json=JsonConvert.DeserializeObject<string>(json);
after this I deserialized it using both Serializer (MS and Newtonsoft) and everything is ok
var jd = JsonConvert.DeserializeObject<List<GetWesLotToGenerateReturn>>(json);
var jdm = System.Text.Json.JsonSerializer.Deserialize<List<GetWesLotToGenerateReturn>>(json);
How to deserialize JSON data in MVC
Your SessionStoreID
class is incorrect so it will not map.
You need to do the following:
public class SessionStore
{
[JsonProperty("Table")]
public List<SessionStoreID> SessionStoreId { get; set;}
}
public class SessionStoreID
{
[JsonProperty("SessionId")]
public string Session { get; set; }
public string Data { get; set; }
[JsonProperty("Expiration")]
public DateTime ExpiredDate { get; set; }
}
SessionStore ServiceInfo = JsonConvert.DeserializeObject<SessionStore>(responseBody);
You need to use the [JsonProperty(string)]
attribute as your property names do not match the Json key names so it cannot automatically populate those fields in the object.
How can I deserialize JSON to a simple Dictionarystring,string in ASP.NET?
Json.NET does this...
string json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
More examples: Serializing Collections with Json.NET
How to deserialize json data coming from web api directly
In that case use it without list
var exam = new TestJson();
exam = JsonConvert.DeserializeObject<TestJson>(json);
Deserialize JSON containing property of type object
In order to support the dynamic deserialization of the JSON content, you can use a custom JsonConverter that analyzes the JSON content and creates the correct class. The following sample shows the deserialization if the value can be an integer or an object:
Sample JSON
[
{
"Name": "A",
"Info": { "Value": 3 }
},
{
"Name": "B",
"Info": {
"Value": { "Text": "ABC" }
}
}
]
.NET types
public class ComplexData
{
public string Name { get; set; }
public Info Info { get; set; }
}
public class Info
{
// other properties
[JsonConverter(typeof(ValueJsonConverter))]
public object Value { get; set; }
}
public class ComplexSubData
{
public string Text { get; set; }
}
Custom JSON converter
public class ValueJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Integer)
return Convert.ToInt32(reader.Value);
return serializer.Deserialize<ComplexSubData>(reader);
}
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
The custom converter is applied to the property using the JsonConverter
attribute. If your structure is more complex, you can adjust the ReadJson
method to discern between the types.
How to Deserialize json Object on gridview?
@Chetan Ranpariya had correct me. Thank you
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public IList<Namedata> namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
string username = "myuser";
string password = "myuserpass";
byte[] byteArray = Encoding.UTF8.GetBytes("{\"name\":\"" + Name.Text + "\",\"id\":\"1\"}");
WebRequest request = WebRequest.Create("http://myservice/Service4.svc/s_name");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)));
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream = request.GetResponse().GetResponseStream();
var result = (new StreamReader(stream).ReadLine());
var exampleObj = JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = exampleObj.s_name.namedatas
}
Related Topics
In C# Check That Filename Is *Possibly* Valid (Not That It Exists)
C# Optional Parameters on Overridden Methods
Icecast 2: Protocol Description, Streaming to It Using C#
How to Hide a Column (Gridview) But Still Access Its Value
Problem Parsing Currency Text to Decimal Type
How to Restrict/Control the Navigation Routes the User Can Visit Based on Login Status/Role
Why Are Private Fields Private to the Type, Not the Instance
How to Flatten Nested Objects with Linq Expression
HTML Agility Pack Strip Tags Not in Whitelist
Differencebetween a Property and a Variable
Signing and Verifying Signatures with Rsa C#
Navigation Property Should Be Virtual - Not Required in Ef Core
Where's the Datetime 'Z' Format Specifier
How to Set the Default Xml Namespace for an Xdocument