I need to serialize json file which includes xml inside - c#

I have JSON and I need to deserialize it.Json file includes XML inside. Any suggestions?
{"nt":0,"r":true,"o":[{"test":"20fgfgdfgdfAZ20AIgdg151","fddf":"ZregrIPgdffgfSgfg","d":"<DataPDU xmlns="urn:cma:stp:xsd:stp.1.0">
<Body>
</AppHdr>
<Document xmlns="urn:iso:">
.....
</Document></Body>
</DataPDU>"}]}

It appears as though your JSON string is invalid. You have quotation marks unescaped in the o[0].d, or the XML section. I have provided a version of the JSON with the escaped quotation marks below.
{
"nt": 0,
"r": true,
"o": [
{
"test": "20fgfgdfgdfAZ20AIgdg151",
"fddf": "ZregrIPgdffgfSgfg",
"d": "<DataPDU xmlns=\"urn:cma:stp:xsd:stp.1.0\"><Body></<Document xmlns=\"urn:iso:\"> ..... </Document></Body></DataPDU>"
}
]
}
Using .NET Core 3.1 and the System.Text.Json namespace you can deserialize the above json using something along the lines:
async Task Main()
{
string fileName = "ExampleJson.txt";
Example example = null;
using (FileStream fs = File.OpenRead(fileName))
{
example = await JsonSerializer.DeserializeAsync<Example>(fs);
}
}
Documentation on using the System.Text.Json namespace can be found here.

Note that " has to change to \" in your xml-STRING, understood that code won't work . ;)
using System.Text.Json;
public myJson()
{
string json = "<json>";
Rootobject jsonObject = JsonConvert.DeserializeObject<Rootobject>(json);
}
public class Rootobject
{
public int nt { get; set; }
public bool r { get; set; }
public O[] o { get; set; }
}
public class O
{
public string test { get; set; }
public string fddf { get; set; }
public string d { get; set; }
}

Related

How to deserialize JSON file to C# object by section

I have 2 C# class:
public class Light
{
public int Brightness { get; set; }
public string Mode { get; set; }
}
public class AirConditioner
{
public int Temperature{ get; set; }
public string Mode { get; set; }
}
JSON file format:
{
"Light": {
"Brightness": 5,
"Mode": "On"
},
"AirConditioner": {
"Temperature": 25,
"Mode": "Cooling"
}
}
I want to parse JSON file to C# by section, something like this:
var light = JsonDeserialize<Light>.(FileSection["Light"]);
var aircon = JsonDeserialize<AirConditioner>.(FileSection["AirConditioner"]);
What I want is the same as Asp.Net Core configuration work:
var light = new Light();
Configuration.GetSection("Light").Bind(light);
It will be better if I do not need to install other packages.
Thank you for your help.
Update:
The problem is how to get a section of the JSON file.
If I can get the Light section like this:
var lightString = JsonFile.GetSection("Light");
Then I can simply deserialize with System.Text.Json namespace:
var light = JsonSerializer.Deserialize<Light>(lightString);
I have done this by creating a parent class that holds the Light and AirConditioner properties.
The parent Class:
public class Devices
{
public Light Light {get;set;}
public AirConditioner AirConditioner {get;set;}
}
Then you can de-serialize into the Devices and access the light and airconditioner.
var devices = JsonDeserialize<Devices>.(myjsonfilecontent);
var light = devices.Light;
var aircon = devices.AirConditioner;
I think you're looking for https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm in Newtonsoft's JSON.Net
It allows for manipulating of a whole JSON object as very generic JOBject and locating and converting only the parts you need.
In your example this looks something like the following. This code uses the newtonsoft.json package.
using System;
using Newtonsoft.Json.Linq;
namespace SO_67293726
{
public class Light
{
public int Brightness { get; set; }
public string Mode { get; set; }
}
public class AirConditioner
{
public int Temperature { get; set; }
public string Mode { get; set; }
}
class Program
{
public static string JsonString =>
#"{
""Light"": {
""Brightness"": 5,
""Mode"": ""On""
},
""AirConditioner"": {
""Temperature"": 25,
""Mode"": ""Cooling""
}
}";
static void Main(string[] args)
{
var jobject = JObject.Parse(JsonString);
var light = jobject["Light"].ToObject<Light>();
var aircon = jobject["AirConditioner"].ToObject<AirConditioner>();
}
}
}

deserializing json to c# object

my C# is not well but I want to deserializing this my json file to C# object:
[
{
"command":"",
"name":"eee",
"children":
[
{
"command":"Report",
"name":"x",
"children":[],
"path":"wwwwww",
"params":
{
"PeriodType":"1i",
"District":"0i"
}
},...
],
"path":"",
"params":{}
},...
for this schema I have created this object:
[DataContract]
public class ListCommands
{
[DataMember]
public List<Commands> commandList { get; set; }
[DataContract]
public class Commands
{
[DataMember]
public string command { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public string path { get; set; }
[DataMember(Name = "params")]
public Params parameters { get; set; }
[DataMember]
public List<Commands> children { get; set; }
}
}
}
and :
public class Params
{
[DataMember]
public string PeriodType { get; set; }
[DataMember]
public string District { get; set; }
}
}
and I am using this code for deserializing json to c# object:
public static void ReadJsonFile()
{
ListCommands comList = new ListCommands();
//List<Commands> comList = new List<Commands>();
string root = HttpContext.Current.Server.MapPath("~/File");
using (FileStream stream = File.OpenRead(root + "\\commands.json"))
comList = (ListCommands)new DataContractJsonSerializer(typeof(ListCommands)).ReadObject(stream);
}
}
but unfortunately I got this error:
Additional information: There was an error deserializing the object of type Notifications.Contracts.ListCommands. Encountered unexpected character 'ï'.
Where is the problem?I have a json file and I want to read this file and then convert to the c# object.
The data format for deserialization differs.
Change json data.
{
"commandList":[
{
"command":"",
"name":"eee",
"children":
[
{
"command":"Report",
"name":"x",
"children":[],
"path":"wwwwww",
"params":
{
"PeriodType":"1i",
"District":"0i"
}
}
],
"path":"",
"params":{}
}]
}
or 2. Change the deserialization target type
comList.commandList = (List<ListCommands.Commands>)new DataContractJsonSerializer(typeof(List<ListCommands.Commands>)).ReadObject(stream);
According suggestion of #SirRufo
1- I have used of Json.Net in this way:
string root = HttpContext.Current.Server.MapPath("~/File");
FileStream stream = File.OpenRead(root + "\\commands.json");
StreamReader reader = new StreamReader(stream);
var comList = JsonConvert.DeserializeObject<dynamic>(reader.ReadToEnd());
and above error gone.
2- By this link I could run previously code:
enter link description here
One of the reasons for this could be that the input file that contains the JSON-encoded data is created with a binary encoding or it has a Byte Order Mark(BOM) byte sequence for a binary encoded file.
For e.g. The UTF-8 representation of the BOM is the byte sequence (0xEF,0xBB,0xBF) in the beginning of the file.
**Note:** You will see this if you created a .JSON file(or a binary file) using visual studio.

how to get "start" item value using C# linq query?

[{"service":"xxx",
"processes":
[
{
"name":"tomcat",
"command":{
"start": "/server/tomcat01/bin/tomcat01.sh start",
"stop": "/server/tomcat01/bin/tomcat01.sh stop",
"restart": "/server/tomcat01/bin/tomcat01.sh restart",
}
}
]
}]
how to get start item value with using c# linq?
Given the following concrete classes:
public class Command
{
public string start { get; set; }
public string stop { get; set; }
public string restart { get; set; }
}
public class Process
{
public string name { get; set; }
public Command command { get; set; }
}
public class Services
{
public string service { get; set; }
public List<Process> processes { get; set; }
}
You can deserialize the json and retrieve a list of all starts with the following:
var json = #"[{""service"":""xxx"", ""processes"": [{""name"":""tomcat"", ""command"":{""start"":""/server/tomcat01/bin/tomcat01.shstart"", ""stop"":""/server/tomcat01/bin/tomcat01.shstop"", ""restart"":""/server/tomcat01/bin/tomcat01.shrestart"", } } ] }]";
var deserialized = JsonConvert.DeserializeObject<List<Services>>(json);
var starts = deserialized.Select(x => x.processes.Select(p => p.command?.start));
Using the Json.Net LINQ-to-JSON API you could do this:
string command = JToken.Parse(json)
.SelectMany(jo => jo.SelectToken("processes"))
.Select(jo => (string)jo.SelectToken("command.start"))
.FirstOrDefault();
...which would return /server/tomcat01/bin/tomcat01.sh start given your JSON input.
Fiddle: https://dotnetfiddle.net/Ft3q2C
It seems that you want to deserialize your json string into C# class.
JavaScriptSerializer jss= new JavaScriptSerializer();
CustomClass tempClass = jss.Deserialize<CustomClass>(jsonString);
jsonString is json data which you mentioned in your question. You can then use linq over your class.

Cannot deserialize the JSON array

I have Json like below:
[
{
"name": "ts.DatumVon",
"value": "29.10.2015"
},
{
"name": "ts.Von",
"value": "8:00"
},
{
"name": "ts.Bis",
"value": "16:30"
}
]
for this class:
public class TSInfo
{
public TimeSaver ts { get; set; }
[Display(Name = "Status")]
public TSStatus tsStatus { get; set; }
[Display(Name = "Typ")]
public TSTyp tsTyp { get; set; }
public TSAuswahlSteps step { get; set; }
}
How to deserialize this Json string in controller method?
EDIT:
I hope that clarifies it.
public class TimeSaver
{
public DateTime DatumVon { get; set; }
public TimeSpan Von { get; set; }
public TimeSpan Bis { get; set; }
}
I tried something like this:
string tsi = [{"name":"ts.DatumVon","value":"29.10.2015"},{"name":"ts.Von","value":"8:00"},{"name":"ts.Bis","value":"16:30"}]
var dict = JsonConvert.DeserializeObject<List<Dictionary<String,String>>(tsi);
The JSON you provided is a list of dictionaries. So you can deserialize it (using NewtonSoft.Json) like this:
string json = "your json";
var result = JsonConvert.Deserialize<List<Dictionary<String,String>>(json);
How you map the result to your class is up to you.
EDIT the above makes no sense. Sorry for that.
Well, your JSON gave me some headache but I think I fixed it.
The JSON is an array of KeyValuePairs. Every pair describes an attribute of your TimeSaver class. The array as an whole describes the complete class. I don't know of an easy way to convert this JSON to a C# class. What complicates the problem even more is the fact that every attribute has some sort of namespace prefix: ts. The final complication is the date format. That's not a format that's recognized automatically.
My solution converts the JSON to a new JSON describing a TimeSaver object. This new JSON is then deserialized using JsonConvert.
One issue still remains: the TimeSaver.DateVon has become a string.
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
string tsi = "[{\"name\":\"ts.DatumVon\",\"value\":\"29.10.2015\"},{\"name\":\"ts.Von\",\"value\":\"8:00\"},{\"name\":\"ts.Bis\",\"value\":\"16:30\"}]";
var attributes = JsonConvert.DeserializeObject<List<NameValuePair>>(tsi);
attributes = attributes
.Select(item => new NameValuePair { Name = item.Name.Replace("ts.", ""), Value = item.Value })
.ToList();
var newJson = "{" + String.Join(",", attributes.Select(item => String.Format("\"{0}\":\"{1}\"", item.Name, item.Value))) + "}";
Console.WriteLine(newJson);
var ts = JsonConvert.DeserializeObject<TimeSaver>(newJson);
Console.WriteLine(ts.DatumVon);
Console.WriteLine(ts.Von);
Console.WriteLine(ts.Bis);
}
}
public class NameValuePair
{
public string Name { get; set; }
public string Value { get; set; }
}
public class TimeSaver
{
public String DatumVon { get; set; }
public TimeSpan Von { get; set; }
public TimeSpan Bis { get; set; }
}

Deserialize Json from file in C#

I've managed to find a solution without removing the paths from the keys.Thanks for the help guys, and also pointing out problems, I really appreciate it! :)
Loaded the Json to a string, deserialized it into a dynamic, ran a foreach through it, and added to a List with ResFiles in it.
static void loadJson()
{
List<ResFile> fileList = new List<ResFile>();
string jsonString = File.ReadAllText(jsonPath);
dynamic files = JsonConvert.DeserializeObject(jsonString);
foreach (var f in files.objects)
fileList.Add(new ResFile(f.Name, f.Value.hash.ToString(), (int)f.Value.size.Value));
}
I'm trying to deserialize some Json file in C# with Newtonsoft's Json library.
The files are named after it's hash, not the real file name and I want to rename them back to the proper names, so like this:
10a54fc66c8f479bb65c8d39c3b62265ac82e742 >> file_1.ext
The Json file:
{
"files": {
"file_1.ext": {
"hash": "10a54fc66c8f479bb65c8d39c3b62265ac82e742",
"size": 8112
},
"file_2.ext": {
"hash": "14cfb2f24e7d91dbc22a2a0e3b880d9829320243",
"size": 7347
},
"file_3.ext": {
"hash": "bf7fadaf64945f6b31c803d086ac6a652aabef9b",
"size": 3838
},
"file_4.ext": {
"hash": "48f7e1bb098abd36b9760cca27b9d4391a23de26",
"size": 6905
}
}
}
I've tried deserialize with this:
static void loadJson()
{
using (StreamReader reader = new StreamReader(jsonPath))
{
string json = reader.ReadToEnd();
dynamic files = JsonConvert.DeserializeObject(json);
}
}
The deserialization itself working, but I don't know how to loop through them.
I've also tried to do this:
class ResFile
{
public string name;
public string hash;
public int size;
}
And somehow force the deserialization to use this, but it didn't work of course.
According to your sample json, your classes would be:
public class ResFile
{
public string hash { set; get; }
public int size { set; get; }
}
public class ResRoot
{
public Dictionary<string, ResFile> Files { set; get; }
}
You can deserialize as
var res = JsonConvert.DeserializeObject<ResRoot>(File.ReadAllText(filename));
foreach(var f in res.Files)
{
Console.WriteLine("Name={0} Size={1}", f.Key, f.Value.size);
}
Please follow the C# conventions and do not expose member variables as public or start property names with lower case. In order to make your conventional objects deserializable, you could use the System.Runtime.Serialization DataContract and DataMember attributes. DataContract indicates that an object of this type is serializable and DataMember is used to specify a property's serialization name.
class ResFile
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "hash")]
public string Hash { get; set; }
[DataMember(Name = "size")]
public int Size { get; set; }
public ResFile () { }
}
[DataContract]
class ResFileCollection
{
[DataMember(Name ="files")]
public Dictionary<string, ResFile> Files { get; set; }
}
And here is the deserialization:
string json = File.ReadAllText("data.json");
var files = JsonConvert.DeserializeObject<ResFileCollection>(json);
foreach(KeyValuePair<string, ResFile> f in files.Files)
{
Console.WriteLine("{0} {1} {2}", f.Key, f.Value.Name, f.Value.Hash);
}
Serialized property names should also be shorter for better performance. An example:
[DataMember(Name="src")]
public string SourcePath { get; set; }

Categories