This question already has answers here:
Deserialize JSON with C#
(10 answers)
Closed 2 years ago.
I'm trying to extract specific data, in this case "Name" from a JSON file so that I can use it for the rest of my code later.
My current code where I load JSON:
public static void LoadJson()
{
using (StreamReader r = new StreamReader(#"C:\Users\Work\Documents\MyJson.json"))
{
string json = r.ReadToEnd();
var o = JsonConvert.DeserializeObject<JObject>(json);
var h = o.Value<JObject>("Data")
.Value<JArray>("Accounts");
Console.WriteLine(h[0]);
}
}
JSON example:
{
"Data": {
"Accounts": [
{
"Name": "owner",
"Address": "123456"
},
{
"Name": "Lerris",
"Address": "179672"
}
]
}
}
The output I get from my code right now:
JSON length is much longer than the one I posted above, but it was just to make an example.
Question:
How do I obtain and define both "Name" and "Address" value so that I can use them for the rest of my code?
I hope you guys will get what I mean. If I weren't specific enough please just say and I'll try to explain again.
See this section:
Use JsonDocument for access to data
Related
This question already has answers here:
How can I deserialize an invalid json ? Truncated list of objects
(3 answers)
Closed 5 years ago.
I have incomplete JSON strings so the JSON is invalid, e.g.:
{
"Id": 0,
"Name": "John",
"Surname": "Smith",
"BadAnswers": ["Answer1", "Answer2"],
"CorrectAnswers": ["Answer3", "Answer4", "Answer5", "Answ
From this JSON I need to extract ID, Name and BadAnswers fields which are complete. I can't just deserialize this string using json.net because JSON is invalid.
Real case contains much more complex JSON with nested objects, lists, etc. but the idea the same.
So the main question is how to extract complete fields from partially completed and thus invalid JSON?
UPDATE 1. I can't make JSON valid by hand because it may be truncated at the random place not only at the place shown in the example. The only thing I know is that all required properties are present in truncated JSON. But if there any way to make JSON valid using json.net or any other library it would be a nice solution.
UPDATE 2. However there is already an answer to the question it is a quite low-level solution and requires a lot of manual work to manipulate with tokens and do not generalize well to different JSON formats.
The solution for you might be to use a JsonReader
For example, consider more complex JSON like this one:
{
"actions": [
{
"completed": true,
"id": 0
},
{
"completed": true,
"id": 1
}
],
"someProperty": false,
"anotherProperty": true,
"requiredIdProperty": 1,
"requiredArrayProperty": [
{
"nestedIdPropery": 0,
"nestedBoolProperty": true
},
{
"nestedIdPropery": 1,
"nestedBoolProperty": false
}
],
"truncatedObject": {
"firstProperty": 990,
"secondProperty": 0,
"thirdPrope
In this case, there are no problems with extracting requiredIdProperty using JsonReader but extracting requiredArrayProperty is painful because I need to manually handle all JSON tokens like JsonToken.ArrayStart and others. Said again, real case may and will contain much more complex JSON with more nested objects and arrays.
The ideal solution I'm looking for is to map JSON to a POCO class ignoring everything starting from the first invalid token or something like this.
The solution for you might be to use a JsonReader
using (FileStream s = File.Open("broken.json", FileMode.Open))
using (StreamReader sr = new StreamReader(s))
using (JsonReader reader = new JsonTextReader(sr))
{
while (reader.Read())
{
// deserialize only when there's "{" character in the stream
if (reader.TokenType == JsonToken.StartObject)
{
//Your code
}
}
}
Is there a reason why you can't just add the two missing characters to the string and then deserialize?
I know this seems too obvious but just incase:
jsonString+="]}";
Then deserialize jsonString.
This question already has an answer here:
Parsing ISO Duration with JSON.Net
(1 answer)
Closed 6 years ago.
I got the following json result from a rest api and I am using Newtonsoft.Json to deserialize it to a c# object.
{
"d": {
"results": [
{
"Aufnr": "4000103",
"Workdate": "/Date(1482796800000)/",
"Beguz": "PT07H30M00S",
}
]
}
}
Aufnr and Workdate are working with String and DateTime, but I got no clue which datatype to use for Beguz
I tried TimeSpan and DateTime and got this error: Error converting value "PT07H30M00S" to type 'System.TimeSpan'. Path '[0].Beguz'
Any ideas?
This is a pure string:
public string Beguz { get; set; }
Of course if you want this PT07H30M00S string to be represented by some complex custom structure you could write a custom JsonConverter to achieve this task. In this converter you will need to provide the logic of how to parse this string back to some custom structure of yours.
This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 6 years ago.
Folks,
I am trying to access a json value from Azure ML rest service but i get a null value all the time, i tried different options but it did not work. Can u please provide ideas.
Json String
{
"Results": {
"output1": {
"type": "table",
"value": {
"ColumnNames": ["Sentiment",
"Score"],
"ColumnTypes": ["String",
"Double"],
"Values": [["negative",
"0.20"],
**["negative",
"0.03"]**]
}
}
}
}
Trying to fetch the value between **
Tried the below.
using Newtonsoft.Json.Linq;
JObject o = JObject.Parse(sentimentvalue);
string valv = (string)o.SelectToken("Results[0].output1[0].Values[0]");
Your JSON path in the SelectToken seems to be wrong.
Try this:
string valv = (string)o.SelectToken("$.Results.output1.value.Values[0][1]");
I have a json string that I will like to grab only the array in the data node. Do I trim using RegEx or what is the best way to extract that portion of the json string?
Here is a sample:
{
"Data":[
{
"Title":"Test Item 1",
"Icon":"pdf",
"PublicationDate":"2013-05-08T18:23:18.037Z"
},
{
"Title":"Test Item 2",
"Icon":"pdf",
"PublicationDate":"2013-05-08T18:23:38.177Z"
}
],
"Count":67
}
Below is what I want to end up with:
[
{
"Title":"Test Item 1",
"Icon":"pdf",
"PublicationDate":"2013-05-08T18:23:18.037Z"
},
{
"Title":"Test Item 2",
"Icon":"pdf",
"PublicationDate":"2013-05-08T18:23:38.177Z"
}
]
How can I do this properly? Sometimes the json string already comes as I need with only the array in the data node, so the logic has to be smart enough to ignore it if it already comes in that format. The reason is because I am feeding both cases to JsonConvert.DeserializeObject<List<dynamic>>(json). Thanks for any help!
After reading your comments, it seems that this is what you need:
var jToken=JToken.Parse(data);
JArray arr;
switch(jToken.Type)
{
case JTokenType.Array:
arr=(JArray)jToken;
break;
case JTokenType.Object:
arr=(JArray)((JObject)jToken)["Data"];
break;
default:
throw new Exception();
}
var output=arr.ToString();
Could you help me for resolving this issue. I have one asp.net application, in this i am using Javascript serializer for serializing a dataset followed by convertion to the list. That code is shown below.
JavaScriptSerializer json = new JavaScriptSerializer();
strJson = json.Serialize(aclDoc);
But, at the time of deserializing i got one ArguementException like Invalid Json Primitives with my Json value. My json value is
[{"Id":"F79BA508-F208-4C37-9904-DBB1DEDE67DB","App_Id":"ScriptFlow","Name":"New form","FriendlyName":"","Read":"Revoke","ReadRule":"a353776f-cbdc-48b7-a15b-4a2316d19b05","Update":"Grant","UpdateRule":"be30c34e-33ec-4c0a-9f09-4fd483f5f1b9","Create":"Revoke","CreateRule":"898dce4d-4709-45b6-8942-d7efb07cbd86","Delete":"Revoke","DeleteRule":"aa14d435-dec8-4ade-ad9b-830ae5ee15d0"}][{"Id":"1","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox1","FriendlyName":"TextBox1","Read":"Grant","ReadRule":"0a2e3c0e-ad8f-4f75-9160-cfd9827ac894","Update":"Grant","UpdateRule":"ecad3cf4-104f-44dc-b815-de039f3a0396"},{"Id":"2","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox2","FriendlyName":"TextBox2","Read":"Grant","ReadRule":"81e0e9ef-09f7-4c25-a58e-d5fdfbd4c2ba","Update":"Grant","UpdateRule":"2047f662-c881-413b-a1f9-69f15bf667fc"}]
The code for deserializing is:
JavaScriptSerializer json = new JavaScriptSerializer();
lstDoc = json.Deserialize<List<ACLDocument>>(value);
return lstDoc;
where lstDoc is a List Collection of type of my class
I got the exception like this:
Invalid JSON primitive:
{"Id":"1","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox1","FriendlyName":"TextBox1","Read":"Grant","ReadRule":"0a2e3c0e-ad8f-4f75-9160-cfd9827ac894","Update":"Grant","UpdateRule":"ecad3cf4-104f-44dc-b815-de039f3a0396"},{"Id":"2","Doc_Id":"858E013C-5775-4FDF-AA1E-2C84053EE39F","Name":"TextBox2","FriendlyName":"TextBox2","Read":"Grant","ReadRule":"81e0e9ef-09f7-4c25-a58e-d5fdfbd4c2ba","Update":"Grant","UpdateRule":"2047f662-c881-413b-a1f9-69f15bf667fc"}].
Please help me for resolving this issue. Thanks in advance
Your input string is really a wrong JSON string. You input consist from two correct JSON strings:
[
{
"Id": "F79BA508-F208-4C37-9904-DBB1DEDE67DB",
"App_Id": "ScriptFlow",
"Name": "New form",
"FriendlyName": "",
"Read": "Revoke",
"ReadRule": "a353776f-cbdc-48b7-a15b-4a2316d19b05",
"Update": "Grant",
"UpdateRule": "be30c34e-33ec-4c0a-9f09-4fd483f5f1b9",
"Create": "Revoke",
"CreateRule": "898dce4d-4709-45b6-8942-d7efb07cbd86",
"Delete": "Revoke",
"DeleteRule": "aa14d435-dec8-4ade-ad9b-830ae5ee15d0"
}
]
and
[
{
"Id": "1",
"Doc_Id": "858E013C-5775-4FDF-AA1E-2C84053EE39F",
"Name": "TextBox1",
"FriendlyName": "TextBox1",
"Read": "Grant",
"ReadRule": "0a2e3c0e-ad8f-4f75-9160-cfd9827ac894",
"Update": "Grant",
"UpdateRule": "ecad3cf4-104f-44dc-b815-de039f3a0396"
},
{
"Id": "2",
"Doc_Id": "858E013C-5775-4FDF-AA1E-2C84053EE39F",
"Name": "TextBox2",
"FriendlyName": "TextBox2",
"Read": "Grant",
"ReadRule": "81e0e9ef-09f7-4c25-a58e-d5fdfbd4c2ba",
"Update": "Grant",
"UpdateRule": "2047f662-c881-413b-a1f9-69f15bf667fc"
}
]
but you can not concatenate two JSON strings. To say exactly what you receive after such concatenating in not more a JSON string.
I recommend you to verify JSON strings in http://www.jsonlint.com/. Just cut and paste the data which you need to verify and click "Validate" button.
To answer the question directly, since everyone thinks this is a Microsoft forum and not answering directly.
The string is sent as a 2 element array. You forgot the '[' in the beginning of the string which denotes that the containing values are an array structure.
Insert the '[' in the beginning of the string and the error should go away.
This is a useful little tool for examining your JSON objects:
http://jsonviewer.codeplex.com/
See if you have any // or commented lines in project.json
Removing this has solved the same problem for me