Normally I open XML stream with File.OpenRead(), deserialize it to class object like so:
var xml = new XmlParse();
using(XmlReader reader = XmlReader.Create(File.OpenRead(@"C:/test/file.xml"))
{
XmlSerializer serializer = new XmlSerializer(typeof(XmlParse));
xml = (XmlParse) serializer.Deserialize(reader);
}
// xml is now deserialized...
then I serialize this deserialized object to JSON just like that:
var json = JsonSerializer.SerializeToString(xml, typeof(XmlParse));
but it's producing a json file with the same scheme as xml file, and that's bothering me.
I want to 'reserialize' it from XML to JSON using TWO different 'parsing classes' with:
public static string Reserialize < XmlType, JsonType > (string path) {
var stream = File.OpenRead(path);
XmlSerializer serializer = new XmlSerializer(typeof(XmlType));
XmlType i;
using(XmlReader reader = XmlReader.Create(stream)) {
i = (XmlType) serializer.Deserialize(reader);
}
string j;
// (System.InvalidCastException)
j = JsonSerializer.SerializeToString(i, typeof(JsonType));
return j;
}
Sample JSON I get by using the same Class as XML:
{
"Time": "1406374539043",
"Events": [
{
"Match": [
{
"Date": "2014-07-26 21:29",
"GameId": 387195098,
"Type": "Soccer",
"League": "Brazil Ser A",
"Live": "No",
"Matchup": [
{
"Team": [
{
"Name": "Criciuma",
"RotationId": 2601,
"Field": "Home"
},
{
"Name": "Vitoria BA",
"RotationId": 2602,
"Field": "Visiting"
},
{
"Name": "Draw",
"RotationId": 2603,
"Field": "Draw"
}
]
}
]
}
]
}
]
}
Desired JSON output:
{
"Time": "1406374539043",
"Matches": [
{
"Date": "2014-07-26 21:29",
"GameId": 387195098,
"Type": "Soccer",
"League": "Brazil Ser A",
"Live": "No",
"Teams": [
{
"Name": "Criciuma",
"RotationId": 2601,
"Field": "Home"
},
{
"Name": "Vitoria BA",
"RotationId": 2602,
"Field": "Visiting"
},
{
"Name": "Draw",
"RotationId": 2603,
"Field": "Draw"
}
]
}
]
}
Using this class to parse JSON (XML class is much different & has more nodes):
{
public class Json
{
public string Time { get; set; }
public List<Matches> Matches { get; set; }
}
public class Matches
{
public string Date { get; set; }
public int GameId { get; set; }
public string Type { get; set; }
public string League { get; set; }
public string Live { get; set; }
public List<Teams> Teams { get; set; }
}
public class Teams
{
public string Name { get; set; }
public int RotationId { get; set; }
public string Field { get; set; }
}
}
(I know it won't work like that, I just simplified this class so it's cleaner and readable)
What would you suggest? How do I convert xml to json with a different style?
No comments:
Post a Comment