Error converting JSON to .Net object in asp.net - c#

I am unable to convert JSON string to .net object in asp.net. I am sending JSON string from client to server using hidden field (by keeping the JSON object.Tostring() in hidden field and reading the hidden field value in code behind file)
Json string/ Object:
[[{"OfferId":"1","OrderValue":"11","HostingTypeID":"3"},
{"OfferId":"1","OrderValue":"11","HostingTypeID":"3"},
{"OfferId":"1","OrderValue":"11","HostingTypeID":"3"},
{"OfferId":"1","OrderValue":"2","HostingTypeID":"3"},
{"OfferId":"1","OrderValue":"2","HostingTypeID":"3"},
{"OfferId":"1","OrderValue":"67","HostingTypeID":"3"},
{"OfferId":"1","OrderValue":"67","HostingTypeID":"3"}],
[{"OfferId":"1","OrderValue":"99","HostingTypeID":"6"}],
[{"OfferId":"1","OrderValue":"10","HostingTypeID":"8"}]]
.Net Object
public class JsonFeaturedOffer
{
public string OfferId { get; set; }
public string OrderValue { get; set; }
public string HostingTypeID { get; set; }
}
Converstion code in code behind file
byte[] byteArray = Encoding.ASCII.GetBytes(HdnJsonData.Value);
MemoryStream stream = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonFeaturedOffer));
object result= serializer.ReadObject(stream);
JsonFeaturedOffer jsonObj = result as JsonFeaturedOffer;
While converting i am getting following error:
Expecting element 'root' from namespace ''.. Encountered 'None' with name '', namespace ''.

Unfortunately, none of the proposed solutions solve the real source of the problem. This exception means that your deserializer tries to read from the end of a stream.
The solution is to rewind the stream to the beginning, ie. set the stream.Position = 0; before deserialization.
Also, as the comments mention, if you used a StreamWriter you need to flush it before using the stream.

Instead of doing this manually I would recommend using the built in lightweight JavaScriptSerializer. No attributes are required on the classes you want to serialize/deserialize.
It's also more flexible and faster than the DataContractJsonSerializer, since it does not have to care about all the wcf stuff. Additionally it has generic overloads that make it very simple to use AND it can also handle anonymous types.
Serialization:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var objectAsJsonString = serializer.Serialize(objectToSerialize);
Deserialization:
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
JsonFeaturedOffer deserializedObject = serializer.Deserialize<JsonFeaturedOffer>(s_JsonBaseDate);
To make it even easier you can create Extension methods that will give you json serialization/deserialization directly on the objects/strings.

If you want the class to auto-magically serialize into json/xml or deserialize in the object you need to decorate it with some serializable attributes:
[Serializable, XmlRoot("JsonFeaturedOffer"), DataContract(Name="JsonFeaturedOffer")]
public class JsonFeaturedOffer
{
[XmlElement ("OfferId"), DataMember(Name="OfferId")]
public string OfferId {get; set;}
... and so on

If this is an array of arrays of JsonFeaturedOffers, shouldn't it be:
byte[] byteArray = Encoding.ASCII.GetBytes(HdnJsonData.Value);
MemoryStream stream = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(JsonFeaturedOffer[][]));
object result= serializer.ReadObject(stream);
JsonFeaturedOffer[][] jsonObj = result as JsonFeaturedOffer[][];

Related

How to only serialize a special property's value to json

YamlDotNet can deserialize a yaml document which contain json.
Suppose there is a yaml document as input like below.
fieldA: a
fieldB:
- { "subFieldA": "a1","subFieldB": "b1" }
- { "subFieldA": "a2","subFieldB": "b2" }
Then, I deserialize it and re-serialize.
class Program
{
static void Main(string[] args)
{
using var sr = new StreamReader("test.yaml");
var deserializer = new DeserializerBuilder()
.WithNamingConvention(CamelCaseNamingConvention.Instance)
.Build();
var output = deserializer.Deserialize<Temp>(sr);
var serializer = new SerializerBuilder()
.Build();
Console.WriteLine(serializer.Serialize(output));
}
}
public class Temp
{
public string FieldA { get; set; }
public List<Dictionary<string, string>> FieldB { get; set; }
}
I would get output like below.
FieldA: a
FieldB:
- subFieldA: a1
subFieldB: b1
- subFieldA: a2
subFieldB: b2
But I want the property FieldB still be serialized to json.
In other words, I want to get a output same as input.
Is there a way to use YamlDotNet to achieve this effect, please?
YamlDotNet is only used for serializing and deserializing YAML. Use the .NET serialization library if all you want to do is actually serialize that dictionary. Obviously the string property cannot do anything with unless it's part of the dictionary.
using System.Text.Json;
var temp = new Temp();
temp.Dict = new Dictionary<string, string>();
temp.Dict.Add("hello", "world");
string json = JsonSerializer.Serialize(temp.Dict);
If you're asking if you can put JSON into YAML, sure, just turn it into a json string first, and add that string as a property of a separate class to serialize into YAML. I don't believe there's a way to automatically get a YAML library to be serializing portions of its stuff into JSON. You can't mix and match.

Loading a .json file into c# program

I am trying to move my website from XML based config files to JSON based ones. Is there a way to load in a .json file in so that it turns into the object? I have been searching the web and I cannot find one. I already have the .xml file converted and saved as a .json. I would rather not use a 3rd party library.
You really should use an established library, such as Newtonsoft.Json (which even Microsoft uses for frameworks such as MVC and WebAPI), or .NET's built-in JavascriptSerializer.
Here's a sample of reading JSON using Newtonsoft.Json:
JObject o1 = JObject.Parse(File.ReadAllText(#"c:\videogames.json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(#"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject) JToken.ReadFrom(reader);
}
Another good way to serialize json into c# is below:
RootObject ro = new RootObject();
try
{
StreamReader sr = new StreamReader(FileLoc);
string jsonString = sr.ReadToEnd();
JavaScriptSerializer ser = new JavaScriptSerializer();
ro = ser.Deserialize<RootObject>(jsonString);
}
you need to add a reference to system.web.extensions in .net 4.0 this is in program files (x86) > reference assemblies> framework> system.web.extensions.dll and you need to be sure you're using just regular 4.0 framework not 4.0 client
As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;
JsonSerializer serializer = new JsonSerializer();
MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(#".\path\to\json\config\file.json");
The above code assumes that you have something like
public class MyObject
{
public string prop1 { get; set; };
public string prop2 { get; set; };
}
And your json looks like;
{
"prop1":"value1",
"prop2":"value2"
}
I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.
Use Server.MapPath to get the actual path of the JSON file and load and read the file using StreamReader
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class RootObject
{
public string url_short { get; set; }
public string url_long { get; set; }
public int type { get; set; }
}
public class Program
{
static public void Main()
{
using (StreamReader r = new StreamReader(Server.MapPath("~/test.json")))
{
string json = r.ReadToEnd();
List<RootObject> ro = JsonConvert.DeserializeObject<List<RootObject>>(json);
}
Console.WriteLine(ro[0].url_short);
}
}
Note : Look below link also I have answered for question similar to this.It will be help full for you
How to Parse an example string in C#
I have done it like:
using (StreamReader sr = File.OpenText(jsonFilePath))
{
var myObject = JsonConvert.DeserializeObject<List<YourObject>>(sr.ReadToEnd());
}
also, you can do this with async call like: sr.ReadToEndAsync().
using Newtonsoft.Json as reference.
Hope, this helps.
See Microsofts JavaScriptSerializer
The JavaScriptSerializer class is used internally by the asynchronous
communication layer to serialize and deserialize the data that is
passed between the browser and the Web server. You cannot access that
instance of the serializer. However, this class exposes a public API.
Therefore, you can use the class when you want to work with JavaScript
Object Notation (JSON) in managed code.
Namespace: System.Web.Script.Serialization
Assembly: System.Web.Extensions (in System.Web.Extensions.dll)

convert javascript object into c# object

I am working on client side programming and I want to convert a javascript object into c# object so that I can save it in database.
Is there any method to achieve this ?
Thanks
javascript:
var obj = {id:0,userName:'Bill'};
c#,
define class:
public class myClass
{
public int id;
public string userName;
}
then transport obj to server (for example using AJAX request), and deserialize, when you need work with object
myClass obj = (new JavascriptSerializer()).Deserialize<myClass>(objJson);
But you can do without deserialization and store objJson string to database
First you will need to pass the JSON object to the server side possibly using a web service in code behind and then you could try this awesome library:
JSON.net
The biggest hurdle you're going to have to overcome here regardless of what serialization/deserialzation technique you decide to go with is how you're going to pass the JSON string from the client side to your code behind where you can use it. For this I recommend using jQuery's AJAX capabilities. This article proved invaluable to me when I was learning how to pass information from the client
For this solution to work you need the type represented by T to be of a type that is decorated with DataContract and DataMember attributes. The DataContractJsonSErializer is WAY better than JavascriptSerializer. This is from some code I wrote for a C# REST client. It does show how to serialize and deserialize generically though. Example object included
[DataContract]
public SampleObject
{
[DataMember("MyProperty")]
public string MyProperty {get;set;}
}
private static byte[] SerializeRequest<T>(string contentType, T request)
{
using (MemoryStream requestObjectStream = new MemoryStream())
{
if (contentType == "applicaton/json")
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(requestObjectStream, request);
}
else if (contentType == "application/xml")
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
serializer.WriteObject(requestObjectStream, request);
}
else
{
throw new Exception("invalid contentType");
}
requestObjectStream.Position = 0;
return requestObjectStream.ToArray();
}
}
private static T DeserializeResponse<T>(string acceptHeader, string responseString)
{
if (acceptHeader == "applicaton/json")
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
MemoryStream responseObjectStream = new MemoryStream(Encoding.UTF8.GetBytes(responseString));
return (T)serializer.ReadObject(responseObjectStream);
}
else if (acceptHeader == "application/xml")
{
DataContractSerializer serializer = new DataContractSerializer(typeof(T));
MemoryStream responseObjectStream = new MemoryStream(Encoding.UTF8.GetBytes(responseString));
return (T)serializer.ReadObject(responseObjectStream);
}
return default(T);
}

How to return serialized to JSON using C#

Im working with a WCF in which i return JSON. But i get messages looking like
"{\"ids\":[\"id\":1,\"id\":34,\"id\":67,\"id\":100,\"id\":133,\"id\":166,\"id\":199]}"
How do I get rid of the first and last qoutation marks?
EDIT:
public class Ids {
public IdDetails[] ids{get;set}
}
public class IdDetails{
public int id {get;set}
}
And here I return JSON
public string GetIds(){
Ids ids = new Ids();
List<IdDetails> idd = new List<IdDetails>();
for(int i=0;i<10; i++){
idd.add(new IdDetails(i+1*33));
}
ids.ids = idd.ToArray();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
string json = jSerialize.Serialize(ids);
return ids;
}
*EDIT 2: SOLVED *
The method shouldn't return a string. It should return a Ids-object. No need to serialize.
Set the ResponseFormat = WebMassageFormat.Json and it will work.
Thanks anyways!
Are you looking with the Visual Studio Debugger at the string?
The debugger shows strings as C# string literal. The string itself doesn't actually contain the leading and trailing " characters and the \ characters.
Console.WriteLine(s);
Output:
{"ids":["id":1,"id":34,"id":67,"id":100,"id":133,"id":166,"id":199]}
JavaScriptSerializer Class
The JavaScriptSerializer class is used internally by the asynchronous communication layer to serialize and deserialize the data that is passed between the browser and the Web server. You cannot access that instance of the serializer. However, this class exposes a public API. Therefore, you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
To serialize an object, use the Serialize method. To deserialize a JSON string, use the Deserialize or DeserializeObject methods. To serialize and deserialize types that are not natively supported by JavaScriptSerializer, implement custom converters by using the JavaScriptConverter class. Then register the converters by using the RegisterConverters method.
I've used it in non-web applications.

.NET serialization of JSON data with dynamic structure (schema)

The web service I consume responces with json data.
it gives resultObject as array:
resultObject:[{object1}, {object2},...] if there more then one object
and it returns
resultObject:{object1} if there only one object.
for serializing in .NET I created a "static" structure of classes to map json schema. But if in one case i've got an array (list) of objects an in other case just one object, how is it possible to handle this situation?
I have found a plethora of ugly solutions to this one, but so far goes:
If you use the System.Web.Script.Serialization.JavaScriptSerializer you have very limited control. If the result data type is simple, you could simply use the DeserializeObject method; it will translate everything into Dictionary and the "resultObject" property will in the first case be a Dictionary while the latter case will turn it into an array of such dictionary. It will not save you the headache of the final translation, but you will get the data into dictionaries which could be considered a first step.
I also attempted to use the KnownTypes and the DataContractJsonSerializer, but alas the datacontract serializer needs "hints" in the form of specially named properties to aid it deserializing. (Why am I using the KnownType attribute wrong?). This is a hopeless strategy if you don't have any control of the serialization which I guess is the case for you.
So now we are down to the butt-ugly solutions of which trial-and-error is my first choice:
When using the ScriptSerializer the conversion will fail with an InvalidOperationException if anything is wrong. I then created two data types one with data-as-arrays and one where data is a single instance (the DataClass is my invention since you do not specify the data types):
[DataContract]
public class DataClass
{
[DataMember]
public string FirstName { get; set; }
[DataMember]
public int BirthYear { get; set; }
public override string ToString()
{
return "FirstName : '" + FirstName + "', BirthYear: " + BirthYear;
}
}
[DataContract]
public class ResultSingle
{
[DataMember]
public DataClass Data { get; set; }
}
[DataContract]
public class ResultArray
{
[DataMember]
public List<DataClass> Data { get; set; }
}
Using these data types it is possible to translate using
JavaScriptSerializer jSer = new JavaScriptSerializer();
var one = jSer.Deserialize<ResultSingle>(jsonWithSingleInstance);
var many = jSer.Deserialize<ResultArray>(jsonWithArray);
But this of course require you to known the data type in advance and you get two different result types. Instead you could choose to always convert to ResultArray. If you get an exception you should convert as ResultSingle and then instantiate the ResultArray and manually add the data object to the Data list:
static ResultArray ConvertJson(string json)
{
ResultArray fromJson;
JavaScriptSerializer jSer = new JavaScriptSerializer();
try
{
fromJson = jSer.Deserialize<ResultArray>(json);
return fromJson;
}
catch (InvalidOperationException)
{
var single = jSer.Deserialize<ResultSingle> (json);
fromJson = new ResultArray();
fromJson.Data = new List<DataClass>();
fromJson.Data.Add(single.Data);
return fromJson;
}
}
static void Main(string[] args)
{
var jsonWithSingleInstance = "{\"Data\":{\"FirstName\":\"Knud\",\"BirthYear\":1928}}";
var jsonWithArray = "{\"Data\":[{\"FirstName\":\"Knud\",\"BirthYear\":1928},{\"FirstName\":\"Svend\",\"BirthYear\":1930}]}";
var single = ConvertJson(jsonWithSingleInstance);
var array = ConvertJson(jsonWithArray);
}
I do not say this is a beautiful solution (it isn't), but it should do the job.
You could also look at json.net which seem to be the json serializer of choice in .NET: How to install JSON.NET using NuGet?
Well, my service provider finally said that it is really a bug.
http://jira.codehaus.org/browse/JETTISON-102
says that is it because of java version that they use.

Categories

Resources