Im getting an ‘SerializationException’ exception when deserializing data’s from json file:
public static T Deserialize(string FilePath)
{
using (FileStream FS = new FileStream(FilePath, FileMode.OpenOrCreate))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(FS) ?? null;
}
}
and this is how im trying to deserialize:
ServiceEntity resultEntity = JsonHelper<ServiceEntity>.Deserialize(DestinationFilePath);
while (resultEntity != null)
{
ListViewItem listViewItem = new ListViewItem(new string[] { resultEntity.ServiceName, resultEntity.ServiceStatus.ToString(), resultEntity.DisplayName });
lvServices.Items.Add(listViewItem);
}
T is this:
[DataContract]
sealed class ServiceEntity
{
[DataMember]
public string DisplayName { get; set; }
[DataMember]
public string ServiceName { get; set; }
[DataMember]
public ServiceControllerStatus ServiceStatus { get; set; }
}
JSON data is : https://pastebin.com/M18GD8yh
2
Answers
Your data is a single line of hundreds of JSON objects. The code reads the entire file and tries to deserialize it into a single C# object. You need to come up with a way to process each object separately. If you have control over the input file, it might be a good start to put the objects into an array, and deserialize that.
what you call a json, is not a valid json string, it is just a collection of json-like peaces in one string. But you can easily fix it
after this you can parse it as Json Array
or you can deserialize it in your c# class
or try your fancy serializer.
Output in a json format
UPDATE
If you have an acces to code to create a json from the c# object it is better to fix it there. IMHO you can use Newtonsonft.Json as a serializer . You can install it using a Nuget package. After this use this code
if you need to save this json in a file