Deserialize JSON string to c# object - c#

My Application is in Asp.Net MVC3 coded in C#.
This is what my requirement is. I want an object which is in the following format.This object should be achieved when I deserialize the Json string.
var obj1 = new { arg1=1,arg2=2 };
After using the below code:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize<object>(str);
The object what i get i.e obje does not acts as obj1
Here, in this example my JSON string is static, but actually JSON string is going to be dynamically generated runtime, so i won't be able get Arg1 and Arg2 all the time.

I think the JavaScriptSerializer does not create a dynamic object.
So you should define the class first:
class MyObj {
public int arg1 {get;set;}
public int arg2 {get;set;}
}
And deserialize that instead of object:
serializer.Deserialize<MyObj>(str);
Not testet, please try.

Use this code:
var result=JsonConvert.DeserializeObject<List<yourObj>>(jsonString);

I believe you are looking for this:
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
JavaScriptSerializer serializer1 = new JavaScriptSerializer();
object obje = serializer1.Deserialize(str, obj1.GetType());

This may be useful:
var serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(json);
Where "json" is the string that contains the JSON values. Then to retrieve the values from the jsonObject you may use
myProperty = Convert.MyPropertyType(jsonObject["myProperty"]);
Changing MyPropertyType to the proper type (ToInt32, ToString, ToBoolean, etc).

solution :
public Response Get(string jsonData) {
var json = JsonConvert.DeserializeObject<modelname>(jsonData);
var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
return data;
}
model:
public class modelname {
public long parameter{ get; set; }
public int parameter{ get; set; }
public int parameter{ get; set; }
public string parameter{ get; set; }
}

Same problem happened to me. So if the service returns the response as a JSON string you have to deserialize the string first, then you will be able to deserialize the object type from it properly:
string json= string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream(), true))
{
json= new JavaScriptSerializer().Deserialize<string>(streamReader.ReadToEnd());
}
//To deserialize to your object type...
MyType myType;
using (var memoryStream = new MemoryStream())
{
byte[] jsonBytes = Encoding.UTF8.GetBytes(#json);
memoryStream.Write(jsonBytes, 0, jsonBytes.Length);
memoryStream.Seek(0, SeekOrigin.Begin);
using (var jsonReader = JsonReaderWriterFactory.CreateJsonReader(memoryStream, Encoding.UTF8, XmlDictionaryReaderQuotas.Max, null))
{
var serializer = new DataContractJsonSerializer(typeof(MyType));
myType = (MyType)serializer.ReadObject(jsonReader);
}
}
4 Sure it will work.... ;)

Related

Json Deserializing not populating properties

I'm deserializing a third party string like this:
{"status":4,"errors":[{"Duplicate Application":"Duplicate Application"}]}
I use my standard extension method:
public static T DeserializeJson<T>(string response)
where T : class
{
var s = new DataContractJsonSerializer(typeof(T));
try {
using (var ms = new MemoryStream()) {
byte[] data = System.Text.Encoding.UTF8.GetBytes(response);
ms.Write(data, 0, data.Length);
ms.Position = 0;
return (T)s.ReadObject(ms);
}
}
catch {
return default(T);
}
}
The class I'm trying to deserialize to looks like this:
[DataContract]
public class ResponseProps
{
[DataMember(Name = "status", Order = 0)]
public string ResponseCode { get; set; }
[DataMember(Name = "lead_id", Order=1)]
public string LeadId { get; set; }
[DataMember(Name = "price", Order=2)]
public decimal Price { get; set; }
[DataMember(Name = "redirect_url", Order = 3)]
public string RedirectUrl { get; set; }
[DataMember(Name = "errors", Order = 4)]
public List<Dictionary<string, string>> Errors { get; set; }
}
I'm using a List of type Dictionary (string, string) for the Errors property because other types I've tried have broken the deserializer - this works in that the serializer no longer throws an exception.
However, I'm now trying to retrieve the data from Errors - I'm using this code:
var cr = XmlHelper.DeserializeJson<ResponseProps>(response);
var errorStore = new HashSet<string>();
foreach (var dict in cr.Errors)
{
foreach (var kvp in dict)
{
errorStore.Add(kvp.Key + ": " + kvp.Value);
}
}
I've done various tests - the dict counts 1, but there are no kvp, so when the loop runs I get no messages.
I'm guessing this is again down to deserialization rather than incorrect looping, but I've not been able to fix it.
Anyone got any advice?
To be able to deserialize such dictionary, you should customize settings of DataContractJsonSerializer with UseSimpleDictionaryFormat set to true:
DataContractJsonSerializerSettings settings = new DataContractJsonSerializerSettings
{
UseSimpleDictionaryFormat = true
};
var s = new DataContractJsonSerializer(typeof(T), settings);
By the way, do you have any reason to use DataContractJsonSerializer with your custom DeserializeJson<T>() method? You could do the same in one line of code with JSON.Net:
var obj = JsonConvert.DeserializeObject<ResponseProps>(str);
JSON.Net is also much more flexible and have a better performance than DataContractJsonSerializer.

Convert comma seperated string to json

I have a comma seperated string value like
100,140
i need to convert that into a json string. that should be like
{"person":[{"id":"100"},{"id":"140"}]}
Please help me with a solution.
Considering you use a Json.net library, I suggest first to split your string to an array by comma andserialize it to a string:
var ids = "100,140".Split(',');
var personsString = JsonConvert.SerializeObject(new { person = ids.Select(x => new { id = x }).ToList()});
In my example, i serialize a dynamic type, but you can implement your custom class Person with ids array.
first split your string and store in an array.
Then convert your strings to jsonObjects.
Add jsonobjects to jsonarray.
follow the below code . it's working.
String split = "100,140";
String[] datas = split.split(",");
JsonArray jsonArry = new JsonArray();
for (String data : datas)
{
JsonObject jsonobj = new JsonObject();
jsonobj.addProperty("id",data);
//jsonobj.SetNamedValue("id", JsonValue.CreateStringValue(data));
jsonArry.add(jsonobj);
}
JsonObject jsonobj2 = new JsonObject();
//jsonobj2.SetNamedValue("person", jsonArry);
jsonobj2.addProperty("person", jsonArry);
//also you can convert the jsonobject to string.
String jsonString = jsonobj2.ToString();
In MVC you have Json serialiser in conrollers. Just create model that describes your json in your case it will be:
public class Model
{
public IEnumerable<Person> person { get; set; }
}
public class Person
{
public int id { get; set; }
}
And then in your controller you are able to do this:
public JsonResult GetData()
{
var str = "100,140"; // your string
Model model = new Model();
//parse string to model
model.person = str.Split(',').Select(x => new Person { id = Convert.ToInt32(x) });
//serialize to json
return Json(model);
}

exception when deserializing json object

I am attempting to deserialize some simple json into the below objects
public class Car
{
public int car_id { get; set; }
public string name { get; set; }
}
public class RootObject
{
public List<Car> cars { get; set; }
}
This is the call I make
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://localhost/WebApiServer/Reference/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("cars").Result;
if (response.IsSuccessStatusCode)
{
HttpContent httpContent = response.Content;
string responseString = httpContent.ReadAsStringAsync().Result;
//error happens here
var deserializeObject = JsonConvert.DeserializeObject<RootObject>(responseString);
}
this is the value of response string from debugger in VS
"\"{ \\\"cars\\\": [{\\\"car_id\\\":46,\\\"name\\\":\\\"Ford-Fiesta\\\"]}}\""
and this is the exception
//exception
Error converting value "{ "cars": [{"car_id":46,"name":"Ford-Fiesta"]}}" to type 'WebApiJson.Program+RootObject'. Path '', line 1, position 62.
this is the json - I am reading it from a file
{ "cars": [{"car_id":46,"name":"Ford-Fiesta"}]}
I have run out of ideas
EDIT:
I just tried
string serializeObject = JsonConvert.SerializeObject(text);
var deserializeObject = JsonConvert.DeserializeObject<RootObject>(serializeObject);
and it is giving me the same problem
EDIT 2
my controller returning the json
public string Cars()
{
string text = System.IO.File.ReadAllText("json.txt");
string serializeObject = JsonConvert.SerializeObject(text);
Debug.WriteLine(serializeObject);
// this fails
var deserializeObject = JsonConvert.DeserializeObject<RootObject>(serializeObject);
return JsonConvert.SerializeObject(text);
}
string text = System.IO.File.ReadAllText("json.txt");
//this line is WRONG!!
string serializeObject = JsonConvert.SerializeObject(text);
//this fails because serializeObject is a double serialized string
//which you try to deserialize to RootOject
var deserializeObject = JsonConvert.DeserializeObject<RootObject>(serializeObject);
return JsonConvert.SerializeObject(text);
You are serializing string into a string.
string serializeObject = JsonConvert.SerializeObject(text);
This is wrong, you should be deserializing to an object.
RootObject obj = JsonConvert.DeserializeObject<RootObject>(text);
This is why your Deserialize fails, because you serialize your initial json into a second string, then try to deserialize it into a RootObject.
Your controller should read something like this
public RootObject Cars()
{
string text = System.IO.File.ReadAllText("json.txt");
RootObject serializeObject = JsonConvert.DeserializeObject<RootObject>(text);
return serializeObject;
}

Serializing .NET object to JSON

I tried the following code to serialize a .NET object to JSON, but i keep getting blank text. What am I doing wrong?
[DataContract]
public class JsonObject2
{
[DataMember(Name = "field1")]
string field1 { get; set; }
[DataMember(Name = "field2")]
string field2 { get; set; }
[DataMember(Name = "field3")]
string[] test = { "heshan", "perera" };
}
The object, I attempt to serialize and display the resulting JSON string in a message box, but all i get is blank.
MemoryStream s = new MemoryStream();
DataContractJsonSerializer dcjs2 = new DataContractJsonSerializer((typeof(JsonObject2)));
JsonObject2 obj2 = new JsonObject2();
dcjs2.WriteObject(s, obj2);
StreamReader r = new StreamReader(s);
String x = r.ReadToEnd();
MessageBox.Show(x);
Try adding:
s.Position = 0;
just before you create the StreamReader.

How to decode a JSON string using C#?

I'm looking for an example code/lib to decode a JSON string using C#.
To encode I can do this:
var data = new Dictionary<string,string>();
data.Add("..", "...");
var json_encoded = new JavaScriptSerializer().Serialize(data);
but how do I decode?
var json_decoded = ??
You can do this:
var data = new Dictionary<string, string>();
data.Add("foo", "baa");
JavaScriptSerializer ser = new JavaScriptSerializer();
var JSONString = ser.Serialize(data); //JSON encoded
var JSONObj = ser.Deserialize<Dictionary<string, string>>(JSONString); //JSON decoded
Console.Write(JSONObj["foo"]); //prints: baa
This will take JSON and convert it to a strongly typed class of which you specify (T)
public static T Deserialize<T>(string json)
{
var obj = Activator.CreateInstance<T>();
using(var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T) serializer.ReadObject(ms);
return obj;
}
}
This will take a class and serialize it as JSON
public static string Serialize<T>(T obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
Note: In the first example you will need to have a backing class to specify what type T is. So if you told it that T is of type User you would need to have this specified somewhere:
public class User
{
public string Username { get; set; }
public string Firstname { get; set; }
}

Categories

Resources