I have to deserialize a JSON response(from a wep API) . The problem is that this API returns JSON with dynamic property. Had it been like
{
"employees":
[{
"employeeCode": "ABC",
"cityId": 123
},{
"employeeCode": "DEF",
"cityId": 234
}]
}
it would have been perfect but the response is string and is returned like:
var response = #"{"ABC": 123, "DEF": 234}";
Where the first property is "EmployeeCode" and the second property is "CityId". How can I use JSON.Net to serialize it into the following class?
public class Employees
{
public string employeeCode {get; set;}
public string cityId {get; set;}
}
Regarding my comment maybe it us better to write the example of what I ment:
string json = #"{""ABC"": 123, ""DEF"": 234}";
var employees = JsonConvert.DeserializeObject<Dictionary<string, int>>(json).Select(x => new Employees() { employeeCode = x.Key, cityId = x.Value });
You'll need:
using System.IO;
using System.Text;
using System.Runtime.Serialization.Json;
public static string Serialize<T>(T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
string retVal = Encoding.UTF8.GetString(ms.ToArray());
return retVal;
}
public static T Deserialize<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms);
ms.Close();
return obj;
}
Related
I am looking for this code: https://dotnetfiddle.net/80dz3V
using System;
using Newtonsoft.Json;
public class Program
{
public class Product
{
public string Name {get; set;}
public DateTime Expiry {get; set;}
public string[] Sizes {get; set;}
}
public void Main()
{
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };
string json = JsonConvert.SerializeObject(product);
Console.WriteLine(json);
object str = "test";
json = JsonConvert.SerializeObject(str);
Console.WriteLine(json);
}
}
To correctly handle Product but to return just test and not "test"
Output:
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
"test"
Wanted Output
{"Name":"Apple","Expiry":"2008-12-28T00:00:00","Sizes":["Small"]}
test
I understand I could just use a wrapper and check for as but I am curious on what if any JSON.net options are available that can accomplish this?
Well if your product is a viewModel maybe you can use automapper to return it like Json or you can use the following method with newtonsoft
var jsonObject = new JObject
{
{"Property1", Obj.Prop1},
{"Property2", Obj.Prop1 },
{"Property3", Obj.Prop1 },
{"Property4", Obj.Prop1 }
};
For example the result would be:
{"Property1": "Test", "Property2": 1, "Property3": "ABC123", "Property4": 123.21 }
I am using this method to form json string and this is working fine. But i can't handle this if it contains more properties. Is there any other better method than this?
string.Format("{0}{1}longUrl{1}:{1}{2}{1}{3}", "{", "\"", longUrl,"}");
The output is
{"longUrl":"http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"}
Well, a "better" way of doing this would be to use a Json library. If this is in the context of an Asp.Net website (in the latter versions), there is the Json.Net library that is automatically referenced. If not, you can use Nuget to add a reference to your project or manually add it, whichever your prefer. You could then do:
JsonConvert.SerializeObject(new { longUrl = longUrl });
Note that you can also just use new { longUrl } and the property name will be the same as your variable name.
You can use JSON.Net library. You can create an entity class which you want to covert to JSON rather than using string formatter.
for e.g.
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
Account account = new Account
{
Email = "james#example.com",
Active = true,
CreatedDate = new DateTime(2013, 1, 20, 0, 0, 0, DateTimeKind.Utc),
Roles = new List<string>
{
"User",
"Admin"
}
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
Console.WriteLine(json);
output:
// {
// "Email": "james#example.com",
// "Active": true,
// "CreatedDate": "2013-01-20T00:00:00Z",
// "Roles": [
// "User",
// "Admin"
// ]
// }
You could just use a JSON serializer such as JSON.NET. Failing that, you can simplify somewhat:
string.Format(#"{{""longUrl"":""{0}""}}", longUrl);
You may use Newtonsoft.Json:
using System.Text;
using Newtonsoft.Json;
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
var d = new
{
longUrl = "http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72",
someOtherProeprty = 1
};
var s = new JsonSerializer();
var sb = new StringBuilder();
using (var w = new StringWriter(sb))
{
s.Serialize(w, d);
}
Console.WriteLine(sb.ToString());
}
}
you can using System.Web.Script.Serialization;
then do
var dict = new Dictionary<string, string>
{
{"longUrl","http://api.themoviedb.org/3/person/12835?api_key=2c50a994de5291887a4e062edd229a72"},
{"anotherUrl", "another Url"}
};
var serializer = new JavaScriptSerializer();
serializer.Serialize(dict);
As an example to create the following JSON string
{
"userId" : "121211-121112",
"accountId": "xhd1121-kdkdj11"
}
use the following string interpolation and formating.
var jsonString = $#"{{
"userId"": ""{user.Id},""
""accountId"": ""{account.Id}""
}}"';
I have a list of a custom object with two properties that needs to be serialized into JSON. Here is the object:
public class IndexData
{
public string ColumnName { get; set; }
public string Data { get; set; }
}
I need the JSON for the List to be returned like this:
{ "IndexData" : [
{ "Column1": "Data1",
"Column2": "Data2"
}
]
}
Is this possible?
List<IndexData> list = new List<IndexData>()
{
new IndexData(){ColumnName="column1",Data="data1"},
new IndexData(){ColumnName="column2",Data="data2"},
};
//Using Json.Net
var json1 = JsonConvert.SerializeObject(
new {IndexData=list.ToDictionary(x => x.ColumnName, x => x.Data)});
//Using JavaScriptSerializer
var json2 = new JavaScriptSerializer().Serialize(
new { IndexData = list.ToDictionary(x => x.ColumnName, x => x.Data) });
Use JavaScriptSerializer
var indexdata = new IndexData();
var json = new JavaScriptSerializer().Serialize(indexdata);
OR DataContractJsonSerializer
MemoryStream s = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(IndexData));
s.Position = 0;
StreamReader sr = new StreamReader(s);
var json = sr.ReadToEnd();
I'm a big fan of Json.Net
You can use the SerializeObject call to simple serialize your object:
var list = new List<IndexData> {new IndexData {ColumnName = "Foo", Data = "Bar"}};
var output = JsonConvert.SerializeObject(list);
output will then be set to
[{"ColumnName":"Foo","Data":"Bar"}]
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.... ;)
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; }
}