C# serialize JSON without property name - c#

maybe this was asked somewhere before, but I don't know how to search for my problem.
I'm using a WebAPI to verify licenses. From this API I get the return JSON string in follwing format.
string json = "[{"status":"error","status_code":"e002","message":"Invalid licence key"}]"
This is my serializer
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl));
ActivationResponseWooSl ar = (ActivationResponseWooSl)js.ReadObject(ms);
}
Now my questions is, how must the "ActivationResponseWooSl" class look like so that the serializer can convert it?
Any help is highly appreciated!
For now it looks like that (what's not workiing):
[DataContract]
public class ActivationResponseWooSl
{
[DataMember(Name = "status")]
public string Status { get; set; }
[DataMember(Name = "status_code")]
public string ErrorCode { get; set; }
[DataMember(Name = "message")]
public string ErrorMessage { get; set; }
}
However when I serialize my json string, all properties are "null".

Your class is correct. Your JSON is an array of object.
Try
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(ActivationResponseWooSl[]));
var arr = (ActivationResponseWooSl[])js.ReadObject(ms);

Related

UWP C# - How to deserialize JsonObject into a class using Windows.Data.Json?

I don't want to use Newtonsoft's Json.Net library. I'm avoiding any third-party dependencies if I can help it in this project.
If I have JSON that looks like this:
{
"has_more_items": false,
"items_html": "...",
"min_position": "1029839231781429248"
}
and I have a class that looks like this:
public class TwitterJson
{
bool hasMore { get; set; } // has_more_items
string rawText { get; set; } // items_html
string nextKey { get; set; } // min_position
}
and I have a JsonObject containing the above JSON:
JsonObject theJson = JsonObject.Parse(result);
How do I deserialize the JsonObject into my class? I've been trying to find a clear example of this, and everything I've found uses Json.Net.
I've been trying to find a clear example of this, and everything I've found uses Json.Net.
Because reinventing existing functionality is a waste of time especially when all the hard work has already been done for you.
If you insist on not using it then you will have to manually construct the object model based on the expected JSON.
For example, assuming publicly available properties
public class TwitterJson {
public bool hasMore { get; set; } // has_more_items
public string rawText { get; set; } // items_html
public string nextKey { get; set; } // min_position
}
Then parsing the above to the desired object model
JsonObject theJson = JsonObject.Parse(result);
var model = new TwitterJson {
hasMore = theJson.GetNamedBoolean("has_more_items"),
rawText = theJson.GetNamedString("items_html"),
nextKey = theJson.GetNamedString("min_position")
};
As mentioned by #Dimith, you need to decorate your class with [DataContract] and [DateMember], Please refer to below code which will convert your JSON into a given object.
// Deserialize a JSON string to a given object.
public static T ReadToObject<T>(string json) where T: class, new()
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
return ser.ReadObject(stream) as T;
}
}
Class:
[DataContract]
public class TwitterJson
{
[DataMember(Name = "has_more_items")]
bool hasMore { get; set; } // has_more_items
[DataMember(Name = "items_html")]
string rawText { get; set; } // items_html
[DataMember(Name = "min_position")]
string nextKey { get; set; } // min_position
}
Sample on how to use:
var result = "{\"has_more_items\": false, \"items_html\": \"...\",\"min_position\": \"1029839231781429248\"}";
var obj = ReadToObject<TwitterJson>(result);
You have to decorate your class with [DataContract] and [DataMember] attributes. Write the json into a memory stream and deserialize using DataContractJsonSerializer
Here is a more elaborated sample.
In addition to #Nkosi's answer below are some Comparisons between JSON.net and other alternatives:
JSON.Net vs DataContractJsonSerializer
JSON.Net vs Windows.Data.Json

DataContractJsonSerializer returning nulls .Net4.0

This is the json string I need to deserialize:
[{"id":5236083584722820,"name":"IT_Projects","accessLevel":"EDITOR"},
{"id":2034305724639108,"name":"IT_Task","accessLevel":"EDITOR"},
{"id":2249810003683204,"name":"On-Hold","accessLevel":"EDITOR"}]
Here is the code:
[DataContract]
public class SSCollection
{
[DataMember]
public List<SSheets> sheetObjects { get; set; }
}
[DataContract]
public class SSheets
{
[DataMember]
public Int64 id { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public string accessLevel { get; set;}
}
using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
memoryStream.Position = 0;
var serializer = new DataContractJsonSerializer(typeof(SSCollection));
SSCollection ss = (SSCollection)serializer.ReadObject(memoryStream);
return ss;
}
I'm not sure how to handle the json string, it appears to be an array but is not named. I've tried with using the SSheets DataContract and with using SSCollection, both return nulls except when I use SSheets i get a 0 for id and nulls for the strings name and accessLevel. Any help will be greatly appreciated. thanks.
AFter reading many other questions on this subject and reading their sugggestions to use Json.Net I have decided to use Newtonsoft.Json. It worked on the first try. .Net DataContract just not worth the hassle. Thanks for your help.

Deserialization of Json without name fields

I need to deserialize the following Json, which according to Jsonlint.com is valid, but ive not come across this before or cannot find examples of similar Json and how to deal with it?
[1,"Bellegrove / Sherwood ","76705","486","Bexleyheath Ctr",1354565507000]
My current system with like this:
Data class:
[DataContract]
public class TFLCollection
{ [DataMember(Name = "arrivals")]
public IEnumerable<TFLB> TFLB { get; set; }
}
[DataContract]
public class TFLB
{
[DataMember]
public string routeName { get; set; }
[DataMember]
public string destination { get; set; }
[DataMember]
public string estimatedWait { get; set; }
}
Deserializer:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(TFLCollection));
using (var stream = new MemoryStream(Encoding.Unicode.GetBytes(result)))
{ var buses = (TFLCollection)serializer.ReadObject(stream);
foreach (var bus in buses.TFLBuses)
{
StopFeed _item = new StopFeed();
_item.Route = bus.routeName;
_item.Direction = bus.destination;
_item.Time = bus.estimatedWait;
listBox1.Items.Add(_item);
My exsiting deserializer works with a full Json stream and iterates through it, but in my new Json I need to deserialize, it only have 1 item, so I wont need to iterate through it.
So is it possible to deserialize my Json example using a similar method than I currently do?
I would say that you are attempting to overcomplicate things. What you have is a perfectly formed json array of strings. If I were you I would deserialize that to an .net array first, and then write a 'mapper' function to copy the values across:
public TFLB BusRouteMapper(string[] input)
{
return new TFLB {
Route = input[x],
Direction = input[y],
};
}
And so on. Of course this assumes that you know what order your json is going to be in, but if you are attempting this in the first place then you must do!

Json string deserialized to array list of objects

Please help!
Getting this error on Deserializing:
Cannot convert object of type 'System.String' to type
'System.Collections.Generic.List'
JSON string from client:
"\"[{\\"id\\":\\"18_0_2_0\\",\\"ans\\":\\"You can enter free
text in place of
*\\"},{\\"id\\":\\"23_1_3_1\\",\\"ans\\":\\"The refresh button\\"},{\\"id\\":\\"11_2_1_2\\",\\"ans\\":\\"False\\"}]\""
Edit: Unescaped (see comments):
[{"id":"18_0_2_0","ans":"You can enter free text in place of *"},{"id":"11_2_1_2","ans":"False"}]
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RawAnswer> ListAnswers = serializer.Deserialize<List<RawAnswer>>(str);
[Serializable]
public class RawAnswer
{
public string QuestionID { get; set; }
public string Answer { get; set; }
public RawAnswer() { }
}
public class AnswerList
{
public List<RawAnswer> RawAnswer { get; set; }
}
Your original json string(before aKzenT's edit) was double escaped and I used var str2 = Regex.Unescape(str); to get the actual string .
public class RawAnswer
{
public string id { get; set; }
public string ans { get; set; }
}
And no need for AnswerList
Now your code can work
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RawAnswer> ListAnswers = serializer.Deserialize<List<RawAnswer>>(str);
The JSON string you receive from the client is itself a string containing the actual JSON string you're looking for. Either fix the client to send you a correct string, or first deserialize this result into a String, and then deserialize that into a List<RawAnswer>.

How can I convert JSON to DataTable using C#

I have a json string and would like to make a DataTable from it.
How can I convert JSON to a DataTable in C#?
Update:
I have used Json.Net as per link provided here
and build 2 class to to handle json string as per below
public class JsonHelper
{
public List<User> userdata { get; set; }
}
public class User
{
public string name { get; set; }
public string id { get; set; }
public DateTime createdDate { get; set; }
}
and use following code to Deserialize
Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
StringReader sr = new StringReader(jsonstr);
Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
object result = json.Deserialize(reader, typeof( JsonHelper));
reader.Close();
return result;
but getting following error
Cannot deserialize JSON array into type 'mynamespace+JsonHelper'.
What should be problem here , please help me to sort out this problem.
thanks.
This post by Rick Strahl may help you out. Under the covers he's using Newtonsoft's JSON.NET libraries to do the heavy lifting.

Categories

Resources