I have JSON that looks like this:
{
"MobileSiteContents": {
"au/en": [
"http://www.url1.com",
"http://www.url2.com",
],
"cn/zh": [
"http://www.url2643.com",
]
}
}
I'm trying to deserialize it into an IEnumerable of classes that look like this:
public class MobileSiteContentsContentSectionItem : ContentSectionItem
{
public string[] Urls { get; set; }
}
public abstract class ContentSectionItem
{
public string Culture { get; set; }
}
Is that possible?
I realise I will probably need to use a Custom JsonConverter for this, but can't find any examples.
I started writing a method to convert using JObject.Parse but not sure if this is the correct / most efficient route to go down:
public IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
var jobject = JObject.Parse(json);
var result = new List<MobileSiteContentsContentSectionItem>();
foreach (var item in jobject.Children())
{
var culture = item.Path;
string[] urls = new[] { "" }; //= this is the part I'm having troble with here...
result.Add(new MobileSiteContentsContentSectionItem { Culture = culture, Urls = urls });
}
return result;
}
You're on the right track. Here are the corrections you need to make:
You're iterating over children of the top-level object expecting to get data that is actually in an object one level further down. You need to navigate to the value of the MobileSiteContents property and iterate over the children of that.
When you take the Children() of the JObject, use the overload that lets you cast them to JProperty objects; that will make it much easier to extract the data you want.
Get the culture from the Name of the JProperty item
To get the urls, get the Value of the JProperty item and use ToObject<string[]>() to convert it to a string array.
Here is the corrected code:
public IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
var jObject = JObject.Parse(json);
var result = new List<MobileSiteContentsContentSectionItem>();
foreach (var item in jObject["MobileSiteContents"].Children<JProperty>())
{
var culture = item.Name;
string[] urls = item.Value.ToObject<string[]>();
result.Add(new MobileSiteContentsContentSectionItem { Culture = culture, Urls = urls });
}
return result;
}
If you like terse code, you can reduce this to a "one-liner":
public IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
return JObject.Parse(json)["MobileSiteContents"]
.Children<JProperty>()
.Select(prop => new MobileSiteContentsContentSectionItem
{
Culture = prop.Name,
Urls = prop.Value.ToObject<string[]>()
})
.ToList();
}
Demo:
class Program
{
static void Main(string[] args)
{
string json = #"
{
""MobileSiteContents"": {
""au/en"": [
""http://www.url1.com"",
""http://www.url2.com"",
],
""cn/zh"": [
""http://www.url2643.com"",
]
}
}";
foreach (MobileSiteContentsContentSectionItem item in Parse(json))
{
Console.WriteLine(item.Culture);
foreach (string url in item.Urls)
{
Console.WriteLine(" " + url);
}
}
}
public static IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
return JObject.Parse(json)["MobileSiteContents"]
.Children<JProperty>()
.Select(prop => new MobileSiteContentsContentSectionItem()
{
Culture = prop.Name,
Urls = prop.Value.ToObject<string[]>()
})
.ToList();
}
public class MobileSiteContentsContentSectionItem : ContentSectionItem
{
public string[] Urls { get; set; }
}
public abstract class ContentSectionItem
{
public string Culture { get; set; }
}
}
Output:
au/en
http://www.url1.com
http://www.url2.com
cn/zh
http://www.url2643.com
I tried this using Json.Net and works fine.
public IEnumerable<MobileSiteContentsContentSectionItem> Parse(string json)
{
dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var result = new List<MobileSiteContentsContentSectionItem>();
var urls = new List<string>();
foreach (var item in jobject.MobileSiteContents)
{
var culture = item.Name;
foreach(var url in item.Value)
urls.Add(url.Value);
result.Add(new MobileSiteContentsContentSectionItem { Culture = culture, Urls = urls.ToArray() });
}
return result;
}
Related
I am trying to deserialize JSON file and want to assign to object ScanResult. var text showing all the values but scanresult showing null some null values. https://gyazo.com/ff2ce386f845394c458a88d43a1f30d8
please suggest if I am missing something.
//MY jSon File SCAN Test 1-1543045410222.json 's code
{
"at": 1543045410222,
"i": 1000,
"s": {
"Sensor1": ["OFF"],
"Sensor2": ["OFF"],
"DataReady1": ["OFF"],
"DataReady2": ["OFF"],
"CV1": [5.0],
"CV2": [6.0]
}
}
//ViewModel Code is as below:
public void ResendScanResult()
{
var ScanActivities = scanActivityManager.GetAll();
foreach (var item in ScanActivities)
{
var scanName = item.ScanName;
var dir = _dataFilePath + scanName + "\\";
var jsonFileName = string.Format("{0}{1}-{2}.json", dir, scanName, item.ScanDateEpoch);
string fileName = Path.GetFileName(jsonFileName);
// ScanResult scanResult = new ScanResult();
var text = File.ReadAllText(jsonFileName);
//var scanResults = JsonConvert.DeserializeObject<ScanResult>(text);
Common.Model.ScanResult scanResult = JsonConvert.DeserializeObject<Common.Model.ScanResult>(text);
var Mvm = MonitorViewModel.Instance;
// TargetProvider target = Mvm.GetTargetProvider(scanResult);
// Mvm.PublishToServer(target, scanResult);
}
}
and my scanRescult class code is as below :
namespace ABX.Common.Model
{
public class ScanResult
{
public ScanResult()
{
At = DateTimeOffset.Now.ToUnixTimeMilliseconds();
Interval = 1;
}
public string Name { get; set; }
public long At { get; set; }
public long Interval { get; set; }
public JObject Values { get; set; }
public string FileName { get; set; }
public JObject ToJson()
{
JObject json = new JObject
{
{ "at", At },
{ "i", Interval },
{ "s", Values }
};
return json;
}
Either rename your class properties to match your JSON, rename your JSON to match your class properties, or implement a custom JsonConverter, where you can implement arbitrary mapping.
I have to read a JSON stream (which I have no control over), which is in the form:
{"files":
{
"/some_file_path.ext": {"size":"1000", "data":"xxx", "data2":"yyy"},
"/other_file_path.ext": {"size":"2000", "data":"xxx", "data2":"yyy"},
"/another_file_path.ext": {"size":"3000", "data":"xxx", "data2":"yyy"},
}
}
So, I have an object named files, which has a number of properties, which have 1) different names every time, 2) different number of them every time, and 3) names with characters which can't be used in C# properties.
How do I deserialize this?
I'm putting this into a Portable Library, so I can't use the JavaScriptSerializer, in System.Web.Script.Serialization, and I'm not sure about JSON.NET. I was hoping to use the standard DataContractJsonSerializer.
UPDATE: I've changed the sample data to be closer to the actual data, and corrected the JSON syntax in the area the wasn't important. (Still simplified quite a bit, but the other parts are fairly standard)
You can model your "files" object as a Dictionary keyed by the JSON property name:
public class RootObject
{
public Dictionary<string, PathData> files { get; set; }
}
public class PathData
{
public int size { get; set; }
public string data { get; set; }
public string data2 { get; set; }
}
Then, only if you are using .Net 4.5 or later, you can deserialize using DataContractJsonSerializer, but you must first set DataContractJsonSerializerSettings.UseSimpleDictionaryFormat = true:
var settings = new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true };
var root = DataContractJsonSerializerHelper.GetObject<RootObject>(jsonString, settings);
With the helper method:
public static class DataContractJsonSerializerHelper
{
public static T GetObject<T>(string json, DataContractJsonSerializer serializer = null)
{
using (var stream = GenerateStreamFromString(json))
{
var obj = (serializer ?? new DataContractJsonSerializer(typeof(T))).ReadObject(stream);
return (T)obj;
}
}
public static T GetObject<T>(string json, DataContractJsonSerializerSettings settings)
{
return GetObject<T>(json, new DataContractJsonSerializer(typeof(T), settings));
}
private static MemoryStream GenerateStreamFromString(string value)
{
return new MemoryStream(Encoding.Unicode.GetBytes(value ?? ""));
}
}
Alternatively, you can install Json.NET and do:
var root = JsonConvert.DeserializeObject<RootObject>(jsonString);
Json.NET automatically serializes dictionaries to JSON objects without needing to change settings.
We need to first convert this Invalid JSON to a Valid JSON. So a Valid JSON should look like this
{
"files":
{
"FilePath" : "C:\\some\\file\\path",
"FileData" : {
"size": 1000,
"data": "xxx",
"data2": "yyy"
},
"FilePath" :"C:\\other\\file\\path",
"FileData" : {
"size": 2000,
"data": "xxx",
"data2": "yyy"
},
"FilePath" :"C:\\another\\file\\path",
"FileData" : {
"size": 3000,
"data": "xxx",
"data2": "yyy"
}
}
}
To make it a valid JSON we might use some string functions to make it looks like above. Such as
MyJSON = MyJSON.Replace("\\", "\\\\");
MyJSON = MyJSON.Replace("files", "\"files\"");
MyJSON = MyJSON.Replace("data:", "\"data:\"");
MyJSON = MyJSON.Replace("data2", "\"data2\"");
MyJSON = MyJSON.Replace(": {size", ",\"FileData\" : {\"size\"");
MyJSON = MyJSON.Replace("C:", "\"FilePath\" :\"C:");
Than we can create a class like below to read the
public class FileData
{
public int size { get; set; }
public string data { get; set; }
public string data2 { get; set; }
}
public class Files
{
public string FilePath { get; set; }
public FileData FileData { get; set; }
}
public class RootObject
{
public Files files { get; set; }
}
Assuming you have a valid JSON you could use JavaScriptSerializer to return a list of objects
string json = "{}"
var serializer = new JavaScriptSerializer();
var deserializedValues = (Dictionary<string, object>)serializer.Deserialize(json, typeof(object));
Alternatively you could specify Dictionary<string, List<string>> as the type argument
strign json = "{}";
JavaScriptSerializer serializer = new JavaScriptSerializer();
var deserializedValues = serializer.Deserialize<Dictionary<string, List<string>>>(json);
foreach (KeyValuePair<string, List<string>> kvp in deserializedValues)
{
Console.WriteLine(kvp.Key + ": " + string.Join(",", kvp.Value));
}
I have a JSON file saved locally that is being opened and read from successfully, but every time I try to parse it it fails. I've checked the JSON online but I can't find fault with it.
{
"Groups": [
{
"UniqueId": "233619708",
"Title": "Partno",
"Customer": "Customer",
"Items": []
}
]
}
I'm using a modified version of the JSON reader included in a sample source in VS, which looks like this:
private async Task GetSampleDataAsync()
{
if (this._groups.Count != 0)
return;
StorageFile file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync("DB.json");
string jsonText = await FileIO.ReadTextAsync(file);
if (jsonText == "") {
await new Windows.UI.Popups.MessageDialog("File Blank!").ShowAsync();
}
JsonObject jsonObject;
if(JsonObject.TryParse(jsonText, out jsonObject))
{ await new Windows.UI.Popups.MessageDialog("File Read Error! Json Couldn't Parse!").ShowAsync();
throw new FormatException(jsonText);
}
if(jsonObject.Count == 0)
{
return;
}
JsonArray jsonArray = jsonObject["Groups"].GetArray();
foreach (JsonValue groupValue in jsonArray)
{
JsonObject groupObject = groupValue.GetObject();
Part group = new Part(groupObject["UniqueId"].GetString(),
groupObject["Title"].GetString(),
groupObject["Customer"].GetString(),
groupObject["Description"].GetString());
foreach (JsonValue itemValue in groupObject["Items"].GetArray())
{
JsonObject itemObject = itemValue.GetObject();
group.Items.Add(new Box(itemObject["UniqueId"].GetString(),
Convert.ToInt16( itemObject["Qty"].GetNumber()),
itemObject["Location"].GetString(),
group.UniqueId));
}
this.Groups.Add(group);
}
}
Any ideas anyone? Every time JsonObject.TryParse runs it returns false, and JsonObject.Parse returns a KeyMissingException.
Thanks.
(btw, I know there's nothing in the items part, I've tried both with and without...)
Have you tried using the other Json conversion method?
JsonConvert.DeserializeObject(jsonText);
I remember from having to grab data from bitcoin API's that when one method didn't work as expected it was worth trying the other one.
I think it had something to do with JObject.Parse being for JSON Objects and JsonConvert.Deserialize being for JSON arrays.
EDIT:
This will parse and deserialize the JSON you provided.
public class MyJsonObject
{
public string UniqueId { get; set; }
public string Title { get; set; }
public string Customer { get; set; }
public string Description { get; set; }
public List<JsonObjectItem> Items { get; set; }
}
public class JsonObjectItem
{
public string UniqueId { get; set; }
public string Qty { get; set; }
public string Location { get; set; }
}
public void ParseJson(string jsonText)
{
JObject jsonObject = JObject.Parse(jsonText);
if(jsonObject != null)
{
JToken token = null;
if(jsonObject.TryGetValue("Groups", out token))
{
foreach (var partData in token.Children())
{
if (!partData.HasValues)
continue;
MyJsonObject obj = partData.ToObject<MyJsonObject>();
Part group = new Part(obj.UniqueId, obj.Title, obj.Customer, obj.Description);
if(obj.Items.Count > 0)
{
foreach (var item in obj.Items)
{
short qty;
if(!Int16.TryParse(item.Qty, out qty))
{
// Decide what to do if is error with parsing qty.
}
group.Items.Add(new Box(item.UniqueId, qty, item.Location, obj.UniqueId));
}
}
}
}
}
}
HOWEVER - Depending upon the exact make up of your 'Part' class, you may even be able to simplify this even further and change:
MyJsonObject obj = partData.ToObject<MyJsonObject>();
to:
Part group = partData.ToObject<Part>();
and that should populate the properties and list of items in one go.
Hope that is helpful
I have some data in the following JSON format that I need to parse:
{
"status":0,
"timestamp":"8:20pm",
"routes":[
{
"directions":[
"E Towne",
"ETP"
],
"routeID":"30"
},
{
"directions":[
"Johnson",
"Observatory"
],
"routeID":"81"
}
]
}
Using json.net, I have got want to get the following output:
30 E Towne – ETP
81 Johnson – Observatory
Using the code below, I get the following incorrect output:
30 E Towne – ETP
81 E Towne – ETP
How do I write out the directions array items to the corresponding routeID item? My code:
public class Route
{
public string routeID { get; set; }
public string directions { get; set; }
}
private void routeClient_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string jsonResults_routes = e.Result;
JObject routeData = JObject.Parse(jsonResults_routes);
JArray routeIdArray = (JArray)routeData["routes"];
JArray routeDirections = (JArray)routeData["routes"][0]["directions"];
List<Route> l = new List<Route>();
for (int i = 0; i < routeIdArray.Count; i++)
{
Route BusRoutes = new Route();
JObject routeIDarrayObject = (JObject)routeIdArray[i];
BusRoutes.routeID = (string)routeIDarrayObject["routeID"];
string sep = " - ";
string bothDirections = String.Join(sep, routeDirections);
List<string> sc = new List<string>();
string[] direction = new string[]{bothDirections};
sc.AddRange(direction);
foreach (string direx in sc)
{
BusRoutes.directions = direx;
}
l.Add(BusRoutes);
}
var newList = l.OrderBy(x => x.routeID).ToList();
lbRoutesData.ItemsSource = newList;
}
#competent_tech is correct in is analysis. If I can propose, I think it'll feel more natural if you work with actual objects. For example:
public class RouteInfo
{
public List<string> Directions { get; set; }
public string RouteID { get; set; }
}
public class RouteData
{
public int Status { get; set; }
public string Timestamp { get; set; }
public List<RouteInfo> Routes { get; set; }
}
And in your method:
var routeData = JsonConvert.DeserializeObject<RouteData>(e.Result);
return routeData.Routes
.Select(r => new Route
{
routeId = r.RouteID,
directions = String.Join(" - ", r.Directions)
})
.OrderBy(r => r.routeId)
.ToList();
Or manipulate your type object in other ways, more naturally.
Edit: For an easy way to generate classes based on a JSON string, go to json2csharp.
This is because your routeDirections is specifically asking for the first element in the array:
JArray routeDirections = (JArray)routeData["routes"][0]["directions"];
You need to move this logic inside the loop and use the current loop indexer:
for (int i = 0; i < routeIdArray.Count; i++)
{
Route BusRoutes = new Route();
JObject routeIDarrayObject = (JObject)routeIdArray[i];
BusRoutes.routeID = (string)routeIDarrayObject["routeID"];
JArray routeDirections = routeIDarrayObject["directions"];
I have the following JSON coming back from a remote API (I cannot modify the JSON returned)
{
"APITicket": {
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
}
Now using JSON.Net to convert to this to a model I have to create 2 models.
public class TicketModel
{
public string location { get; set; }
public string ticket { get; set; }
}
public class TicketContainer
{
public TicketModel APITicket { get; set; }
}
and do something like..
var myObject = JsonConvert.DeserializeObject<TicketContainer>(this.JSONResponse);
and this works well - my problem arises when I have around 50 calls to make to the API and really dont fancy creating a second 'Container' for each. Is there a way to bind the example above directly to the TicketModel?
You can do it this way:
var json = #"
{
'APITicket': {
'location': 'SOMEVALUE',
'ticket': 'SOMEVALUE'
}
}";
//Parse the JSON:
var jObject = JObject.Parse(json);
//Select the nested property (we expect only one):
var jProperty = (JProperty)jObject.Children().Single();
//Deserialize it's value to a TicketModel instance:
var ticket = jProperty.Value.ToObject<TicketModel>();
use Newtonsoft's JArray to customize ur json before deserialize
public List<APITicket> JsonParser(string json)
{
Newtonsoft.Json.Linq.JArray jArray = Newtonsoft.Json.Linq.JArray.Parse(json);
var list = new List<APITicket>();
foreach(var item in jArray)
{
list.Add(
new APITicket { location = item["APITicket"]["location"],
ticket = item["APITicket"]["ticket"]
}
);
}
return list;
}
Modify the JSON so it looks like this
{
"location": "SOMEVALUE",
"ticket": "SOMEVALUE"
}
and do
List<TicketModel> tickets = JsonConvert.DeserializeObject<List<TicketModel>>(this.JSONResponse);
or even
Dictionary<string, string> tickets = JsonConvert.DeserializeObject<Dictionary<string, string>>(this.JSONResponse);
so you don't need any models.