Can't parse JSON in C#? - c#

I am trying to read a local .json file using StreamReader:
My code:
using (var jsonReader = new StreamReader(pathToMyJsonFile))
{
string json = jsonReader.ReadToEnd();
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
Console.WriteLine(item.fuzzy);
}
}
My json:
[
{
"fuzzy": "12345",
"name": "{jon-errand}",
"email": "person#gmail.com",
"lights": "red",
"friends": "Elizabeth",
"traits": {
"Hair": "brown",
"Eyes": "yellow"
}
}
]
I get the exception: Error reading JArray from JsonReader. Current JsonReader item is not an array: StartObject. I have tried looking at the SO answer posted here but I am sure my json is a real array. Without changing the above json, how can I read this json file in a useful way so I can pull out specific fields? Such as getting the email field as person#gmail.com?

var obj = JsonConvert.DeserializeObject<List<Item>>(File.ReadAllText(pathToMyJsonFile));
And your classes
public class Traits
{
public string Hair { get; set; }
public string Eyes { get; set; }
}
public class Item
{
public string fuzzy { get; set; }
public string name { get; set; }
public string email { get; set; }
public string lights { get; set; }
public string friends { get; set; }
public Traits traits { get; set; }
}
EDIT
dynamic array = JsonConvert.DeserializeObject(File.ReadAllText(pathToMyJsonFile));
foreach (var item in array)
{
Console.WriteLine(item.name + " " + item.traits.Hair);
}

You can deserialize in JArray
JArray array = JsonConvert.DeserializeObject<JArray>(json);
foreach (var item in array)
{
Console.WriteLine(item["fuzzy"]); // Prints 12345
}

Related

How to read json string in c#

I am trying to parse manually a string in json. This is how my json look like
{{
"dbViews": [
{
"viewID": 0,
"viewColumns": [
{
"dbTitle": "ColNmid",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
},
{
"dbTitle": "ColNmdelete",
"viewTitle": "string",
"activated": true,
"activatedLabel": "Afficher"
}
]
}
],
"AddViewName": "test"
}}
This is how i am trying to read it.
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.id = obj.dbViews.viewID;
User.viewName = obj.AddViewName;
foreach (var item in obj.viewColumns)
{
if (obj.dbTitle == "ColNmid")
{
User.ColNmid = obj.viewTitle;
}
}
I can only read addViewName, i can't seem to access viewID or viewColumn.
Update:
after the comments I obviously miss the second array. Here my new code witch work
UserViewDto User = new UserViewDto();
dynamic obj = JObject.Parse(json);
User.viewName = obj.AddViewName;
foreach (var view in obj.dbViews)
{
User.id = view.viewID;
foreach (var item in view.viewColumns)
{
if (item.dbTitle == "ColNmid")
{
User.ColNmid = item.viewTitle;
}
}
}
Your json in question is invalid (extra { and } at start and end). It seems that you are using Newtonsoft's Json.NET library. Usual approach is to create model corresponding to your json structure and deserialize it:
public class Root
{
[JsonProperty("dbViews")]
public List<DbView> DbViews { get; set; }
[JsonProperty("AddViewName")]
public string AddViewName { get; set; }
}
public class DbView
{
[JsonProperty("viewID")]
public long ViewId { get; set; }
[JsonProperty("viewColumns")]
public List<ViewColumn> ViewColumns { get; set; }
}
public class ViewColumn
{
[JsonProperty("dbTitle")]
public string DbTitle { get; set; }
[JsonProperty("viewTitle")]
public string ViewTitle { get; set; }
[JsonProperty("activated")]
public bool Activated { get; set; }
[JsonProperty("activatedLabel")]
public string ActivatedLabel { get; set; }
}
var result = JsonConvert.DeserializeObject<Root>();
You don't need to include all properties in your class, you can include only needed ones.
If you don't want to create custom models and want to loop through the JObject properties in your case you can do it for example like that:
var jObj = JObject.Parse(json);
foreach(var view in jObj["dbViews"]) // dbViews is an array
{
Console.WriteLine(view["viewID"]);
foreach (var viewColumn in view["viewColumns"]) // viewColumns is an array
{
Console.WriteLine(viewColumn["dbTitle"]);
}
}

JSON Array to Array List using c#

I'm trying to convert JSON to list, please anyone can help me.
public class User
{
public String id { get; set; }
public String imageURL { get; set; }
public String search { get; set; }
public String status { get; set; }
public String username { get; set; }
}
List<User> users = JsonConvert.DeserializeObject<List<User>>(resp.Body);
JSON
{
"KfWE8S9jWJdWnAZEbOtHTtisNwO2":
{"id":"KfWE8S9jWJdWnAZEbOtHTtisNwO2"
,"imageURL":"https://firebasestorage.googleapis.com/v0/b/bchat-af5e5.appspot.com/o/uploads%2F1542785437375.jpg?alt=media&token=be1ce806-fecf-4081-9dad-f0a20e5d8489"
,"search":"rene vizconde"
,"status":"online"
,"username":"Rene Vizconde"},
"ScpDnyQCyKemXSgdo3jEvZFNxY83":
{"id":"ScpDnyQCyKemXSgdo3jEvZFNxY83"
,"imageURL":"default"
,"search":"yeli potpot"
,"status":"offline"
,"username":"Yeli Potpot"},
"cnPYOdHYWaaLDQmchELLvw85DBf1":
{"id":"cnPYOdHYWaaLDQmchELLvw85DBf1"
,"imageURL":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHilM1ke9pZePBJTobMTcktggiw-UywdqAIpf-VX9nqecKl6b4wQ"
,"search":"bards disc"
,"status":"offline"
,"username":"Bards Disc"},
"tWTbllTxaVM9WQnsNwnBgc3ixLM2":
{"id":"tWTbllTxaVM9WQnsNwnBgc3ixLM2"
,"imageURL":"default"
,"search":"renz angelo"
,"status":"offline"
,"username":"Renz Angelo"}
}
You can simply deserialize your json into Dictionary<string, User> instead of List<User>.
class Program
{
static void Main(string[] args)
{
var data = JsonConvert.DeserializeObject<Dictionary<string, User>>(resp.Body);
foreach (var item in data)
{
User user = item.Value;
Console.WriteLine("id: " + user.id);
Console.WriteLine("imageURL: " + user.imageURL);
Console.WriteLine("search: " + user.search);
Console.WriteLine("status: " + user.status);
Console.WriteLine("username: " + user.username);
Console.WriteLine();
}
Console.ReadLine();
}
}
Output:
There is something wrong in your JSON. Altough its structure is "syntaxly" correct, it was badly designed.
You're naming member of the JSON using ids, and then refers to that ID in each object of thoses members.
Don't Repeat Yourself.
Since the name of the members are dynamic, you can't use that root object to deserialize the JSON. (which is NOT a List<User>, there is no list in that JSON, but objects)
Consider using this structure rather (notice the brackets to create an array of objects)
[
{
"id":"KfWE8S9jWJdWnAZEbOtHTtisNwO2"
,"imageURL":"https://firebasestorage.googleapis.com/v0/b/bchat-af5e5.appspot.com/o/uploads%2F1542785437375.jpg?alt=media&token=be1ce806-fecf-4081-9dad-f0a20e5d8489"
,"search":"rene vizconde"
,"status":"online"
,"username":"Rene Vizconde"
},
{
"id":"ScpDnyQCyKemXSgdo3jEvZFNxY83"
,"imageURL":"default"
,"search":"yeli potpot"
,"status":"offline"
,"username":"Yeli Potpot"
},
{
"id":"cnPYOdHYWaaLDQmchELLvw85DBf1"
,"imageURL":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHilM1ke9pZePBJTobMTcktggiw-UywdqAIpf-VX9nqecKl6b4wQ"
,"search":"bards disc"
,"status":"offline"
,"username":"Bards Disc"
},
{
"id":"tWTbllTxaVM9WQnsNwnBgc3ixLM2"
,"imageURL":"default"
,"search":"renz angelo"
,"status":"offline"
,"username":"Renz Angelo"
}
]

Extract array from JSON object containing multiple types

(Just a heads up, I'm very new to C#)
(See sample code and JSON structure below)
I can't figure out how to pull "data" out of the JSON reponse and put it into a data table. The variable "response" is just raw JSON data. So far I've figured out how to parse the JSON into a JObject...so now it has two members (data, meta). Now I'm trying to figure out how to get joTest["data"] into a DataTable. The handful of attempts I've made, keep giving me an error when it sees the "meta" member. Maybe I shouldn't be using a Data Table?
Also, in case it changes anything, I don't need the "links" from the "data" members.
I've tried searching for "Converting JObject into Data Table" But I'm not finding a lot of useful results.
public void PerformFeed()
{
string response;
response = Blah.SendMessage().Result;
JObject joTest = JsonConvert.DeserializeObject<JObject>(response);
}
Json Data Structure
{
"data": [
{
"Val1": "1234",
"Val2": "foo1",
"Val3": "bar1",
"links": [
{
"rel": "self",
"uri": "/blah/1234"
},
{
"rel": "pricing_data",
"uri": "/blah/1234/pricing_data"
}
]
},
{
"Val1": "5678",
"Val2": "foo2",
"Val3": "bar2",
"links": [
{
"rel": "self",
"uri": "/blah/5678"
},
{
"rel": "pricing_data",
"uri": "/blah/5678/pricing_data"
}
]
}
],
"meta": {
"pagination": {
"total": 2,
"count": 2,
"per_page": 25,
"current_page": 1,
"total_pages": 1,
"links": []
}
}
}
UPDATE: I've figured out a "solution" but I really don't think it's a good solution. I built a datatable and then used a foreach statement on the JObject to populate the data table that way. It seems very inefficient...but for now it works. Hopefully I'll find a better way.
public void PerformFeed()
{
DataTable Items = new DataTable();
Items.Columns.Add("Val1");
Items.Columns.Add("Val2");
Items.Columns.Add("Val3");
string response = Blah.SendMessage().Result;
JObject Data = JObject.Parse(response);
foreach (JObject jo in Data["data"])
{
Items.Rows.Add(jo["Val1"], jo["Val2"], jo["Val3"]);
}
}
There is this really nice online utility that helps extracting C# classes from JSON objects. I think the problem here is with your JSON, you're missing a comma ",". You would easily be able to spot the error with some online JSON formatter / validator. Rest the deserialization is pretty straightforward. Try the following:
JObject obtainedObject = JObject.Parse(JsonString);
Following would be the structure of your obtained object:
public class RequiredClass
{
public IList<Datum> data { get; set; }
public Meta meta { get; set; }
}
public class Datum
{
public string Val1 { get; set; }
public string Val2 { get; set; }
public string Val3 { get; set; }
public IList<Link> links { get; set; }
}
public class Link
{
public string rel { get; set; }
public string uri { get; set; }
}
public class Pagination
{
public int total { get; set; }
public int count { get; set; }
public int per_page { get; set; }
public int current_page { get; set; }
public int total_pages { get; set; }
public IList<object> links { get; set; }
}
public class Meta
{
public Pagination pagination { get; set; }
}
Update:
Here's is how you extract your array and convert that to a DataTable:
JObject jObject = JObject.Parse(json);
JToken dataArray = jObject["data"];
DataTable dt = (DataTable) JsonConvert.DeserializeObject(dataArray.ToString(), (typeof(DataTable)));
To avoid the surplus casting, you can try the following using the class structure already mentioned above:
JObject jObject = JObject.Parse(json);
JToken dataArray = jObject["data"];
List<Datum> requiredList = new List<Datum>();
foreach (var item in dataArray)
{
Datum obj = new Datum();
obj.Val1 = (string) item["Val1"] ?? "";
obj.Val2 = (string) item["Val2"] ?? "";
obj.Val3 = (string) item["Val3"] ?? "";
obj.links = new List<Link>();
foreach(var subItem in item["links"])
{
Link lnk = new Link();
lnk.rel = (string) subItem["rel"] ?? "";
lnk.uri = (string) subItem["uri"] ?? "";
obj.links.Add(lnk);
}
requiredList.Add(obj);
}

Parse error with JSONObject in c# .net

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

How to get an item value of json using C#?

How to get an item value of json using C#?
json:
[{
ID: '6512',
fd: [{
titie: 'Graph-01',
type: 'graph',
views: {
graph: {
show: true,
state: {
group: 'DivisionName',
series: ['FieldWeight', 'FactoryWeight', 'Variance'],
graphType: 'lines-and-points'
}
}
}
}, {
titie: 'Graph-02',
type: 'Graph',
views: {
graph: {
show: true,
state: {
group: 'DivisionName',
series: ['FieldWeight', 'FactoryWeight', 'Variance'],
graphType: 'lines-and-points'
}
}
}
}]
}, {
ID: '6506',
fd: [{
titie: 'Map-01',
type: 'map',
views: {
map: {
show: true,
state: {
kpiField: 'P_BudgetAmount',
kpiSlabs: [{
id: 'P_BudgetAmount',
hues: ['#0fff03', '#eb0707'],
scales: '10'
}]
}
}
}
}]
}]
Above mentioned one is json, Here titie value will be get in a list
please help me...
My code is:
string dashletsConfigPath = Url.Content("~/Content/Dashlets/Dashlets.json");
string jArray = System.IO.File.ReadAllText(Server.MapPath(dashletsConfigPath));
List<string> lists = new List<string>();
JArray list = JArray.Parse(jArray);
var ll = list.Select(j => j["fd"]).ToList();
Here json will be converted in to JArray then
li got fd details then we got tite details on a list
If you just want a List<string> of the "titie" (sic) property values, this should work, using SelectMany:
List<string> result = list.SelectMany(
obj => obj["fd"]
.Select(inner => inner["titie"].Value<string>()))
.ToList()
This assumes that the JSON you posted is made valid by quoting property names.
I would recommend creating a class for your objects and use a DataContractSerializer to deserialize the JSON string.
[DataContract]
public class Container
{
[DataMember(Name="ID")]
public string ID { get; set; }
[DataMember(Name="fd")]
public Graph[] fd { get; set; }
}
[DataContract]
public class Graph
{
[DataMember(Name="title")]
public string Title { get; set; }
[DataMember(Name="type")]
public string Type { get; set; }
}
etc.
This will give you strongly typed classes around your JSON.
I'm not sure how you intend to use the data but you can collect all the titie values from your objects like this:
var arr = JArray.Parse(json);
var query =
from JObject obj in arr
from JObject fd in obj["fd"]
select new
{
Id = (string)obj["ID"],
Titie = (string)fd["titie"],
};
You can use json.net to deserialize json string like this:
public class Item
{
public string ID { get; set; }
public List<FD> fd { get; set; }
}
public class FD
{
public string titie { get; set; }
public string type { get; set; }
public Views views { get; set; }
}
public class Views
{
public Graph graph { get; set; }
}
public class Graph
{
public bool show { get; set; }
public State state { get; set; }
}
public class State
{
public string group { get; set; }
public string[] series { get; set; }
public string graphType { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = #"..."; //your json string
var Items = JsonConvert.DeserializeObject<List<Item>>(json);
List<string> tities = new List<string>();
foreach (var Item in Items)
{
foreach (var fd in Item.fd)
{
tities.Add(fd.titie);
}
}
}
}
First thing is your json format invalid. get the valid json below.
[{
"ID": "6512",
"fd": [{
"titie": "Graph-01",
"type": "graph",
"views": {
"graph": {
"show": true,
"state": {
"group": "DivisionName",
"series": ["FieldWeight", "FactoryWeight", "Variance"],
"graphType": "lines-and-points"
}
}
}
}, {
"titie": "Graph-02",
"type": "Graph",
"views": {
"graph": {
"show": true,
"state": {
"group": "DivisionName",
"series": ["FieldWeight", "FactoryWeight", "Variance"],
"graphType": "lines-and-points"
}
}
}
}]
}, {
"ID": "6506",
"fd": [{
"titie": "Map-01",
"type": "map",
"views": {
"map": {
"show": true,
"state": {
"kpiField": "P_BudgetAmount",
"kpiSlabs": [{
"id": "P_BudgetAmount",
"hues": ["#0fff03", "#eb0707"],
"scales": "10"
}]
}
}
}
}]
}]
And if you want to read items as separate strings use following code.
JArray jObject = JArray.Parse(json);
var ll = jObject.ToList();
You can use Newtonsoft Json Library.
Deserialize your json string with the model objects below
public class JsonWrapper
{
public string ID { get; set; }
public List<Fd> fd { get; set; }
}
public class Fd
{
public string titie { get; set; }
public string type { get; set; }
public Views views { get; set; }
}
public class Views
{
public Graph graph { get; set; }
}
public class Graph
{
public bool show { get; set; }
public State state { get; set; }
}
public class State
{
public string group { get; set; }
public List<string> series { get; set; }
public string graphType { get; set; }
}
Declare on object of JsonWrapper class and deserialize the json string to it.
JsonWrapper jsonWrapper = new JsonWrapper();
jsonWrapper = (JsonWrapper)JsonConvert.DeserializeObject(jsonString, jsonWrapper.getType());
Then you can access all the lists and properties from the jsonWrapper object.

Categories

Resources