I want the JSON array element to be converted as a string.
The JSON looks like this:
[
{
"id":373313181,
"from":"no-reply#email.com",
"subject":"example subject 123",
"date":"2022-01-06 13:22:14"
}
]
I want to get the ID element as a string.
I tried to do like that:
var json = "[{\"id\":373313181,\"from\":\"no-reply#email.com\",\"subject\":\"example subject 123\",\"date\":\"2022-01-06 13:22:14\"}]";
var parse = JObject.Parse(json);
var id = parse["id"].ToString();
Console.WriteLine(id);
So that the output will be like this:
373313181
But that simply just didn't work. Any ideas why?
Parse as JArray and take the first element of the array.
var json = "[{\"id\":373313181,\"from\":\"no-reply#email.com\",\"subject\":\"example subject 123\",\"date\":\"2022-01-06 13:22:14\"}]";
var array = JArray.Parse(json);
var id = (string)array[0]["id"];
And from your question, cast the id to string as below:
var id = (string)array[0]["id"];
OR
var id = array[0]["id"].Value<string>();
Sample Program
My implementation:
using System;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = "[{\"id\":373313181,\"from\":\"no-reply#email.com\",\"subject\":\"example subject 123\",\"date\":\"2022-01-06 13:22:14\"}]";
dynamic test = JsonConvert.DeserializeObject(json);
Console.WriteLine(Convert.ToString(test[0].id));
Console.WriteLine(Convert.ToString(test[0].id).GetType());
}
}
//Output
373313181
System.String
Related
How to convert this json string to Jobject
"{\"user\":{\"id\":373697,\"username\":\"luckygirlxxx123\",\"counter_rechecking\":0,\"user_id\":76131,\"fb_id\":\"100047460285611\"}}";
I need it convert to Jobject like this because i need it to post data to website api . Example :
JObject concac = new JObject();
concac1["id"] = 373697;
concac1["username"] = "luckygirlxxx123";
concac1["counter_rechecking"] = 0;
concac1["user_id"] = 76131;
concac1["fb_id"] = "100047460285611";
Because It inside USER that i dont know how to create jobject with that
this code might help you.
public static void Main(string[] args)
{
string jsonData = "{\"user\":{\"id\":373697,\"username\":\"luckygirlxxx123\",\"counter_rechecking\":0,\"user_id\":76131,\"fb_id\":\"100047460285611\"}}";
var details = JObject.Parse(jsonData);
Console.WriteLine(string.Concat(details["user"]["id"], " " + details["user"]["username"]));
}
The simplest way is by giving those JSON values to the contracture of the object
public JObject(int id, string username, int user_id ....)
then you declare object and you pass values to it
JObject concac = new JObject(concac1["id"], concac1["username"], concac1["user_id"]..... );
The second way is JSON Serialization And Deserialization In C#
How can I take just the first element from a Json?
//take result back
void HandleIncomingMessage(object sender, PEventArgs e)
{
RetMessage += e.Result;
//here can not deserialize correct
var deserialized_message = JsonConvert.DeserializeObject<Message>(RetMessage);
}
Here I am doing the deserialize but because it`s taking the entire object can not parse it correct.
I need just JSON.[0]
Edit: Raw Json :
[{"unique_id":55,"action_name":"INSERT","start_date":"2018-06-11T16:00:00","end_date":"2018-06-11T17:00:00"},"1sddsd","my_channel"]
Deserialize to List<dynamic>, then read the properties of its first element.
//using Newtonsoft.Json;
var input = #"[{""unique_id"":55,""action_name"":""INSERT"",""start_date"":""2018-06-11T16:00:00"",""end_date"":""2018-06-11T17:00:00""},""1sddsd"",""my_channel""]";
var output = JsonConvert.DeserializeObject<List<dynamic>>(input);
Console.WriteLine(output[0].unique_id);
Output:
55
DotNetFiddle
How about getting json string and using JSON.net
//first create object from json
JObject jObject = JObject.Parse(jsonString);
//read unique value
string jUniqueId = jObject["unique_id"];
//or
string firstObject = jObject[0];
the solution is for static,
JObject obj= JObject.Parse(here pass the JSON);
string id= JSON[0]["unique_id"],
string name= JSON[0]["action_name"],
string sdate= JSON[0]["start_date"],
string edate= JSON[0]["end_date"]
dynamic means pass i instead of 0.
From the result of an API call I have a large amount of JSON to process.
I currently have this
Object convertObj = JsonConvert.DeserializeObject(responseFromServer);
I am aware that I could do something like
Movie m = JsonConvert.DeserializeObject<Movie>(responseFromServer);
And then use it like
m.FieldName
m.AnotherField
//etc
Ideally I would like to do something like
var itemName = convertObj["Name"];
to get the first Name value for the first item in the list.
Is this possible, or do I have to create a class to deserialize to?
The reason I do not want to create the class is I am not the owner of the API and the field structure may change.
Edit.
Okay so I created the class as it seems the best approach, but is there a way to deserialize the JSON into a list?
var sessionScans = new List<SessionScan>();
sessionScans = JsonConvert.DeserializeObject<SessionScan>(responseFromServer);
Complains that it cannot convert SessionScan to generic list.
No need to use dynamic, you can simply use JToken which is already does what you expect:
var json = #"
{
""someObj"": 5
}
";
var result = JsonConvert.DeserializeObject<JToken>(json);
var t = result["someObj"]; //contains 5
With .NET 6, this can be done as below,
using System.Text.Json;
using System.Text.Json.Nodes;
string jsonString = #"some json string here";
JsonNode forecastNode = JsonNode.Parse(jsonString)!;
int temperatureInt = (int)forecastNode!["Temperature"]!;
Console.WriteLine($"Value={temperatureInt}");
//for nested elements, you can access as below
int someVal = someNode!["someParent"]["childId"]!.ToString();
Refer this MS docs page for more samples - create object using initializers, make changes to DOM, deserialize subsection of a JSON payload.
You can try with JObject.Parse :
dynamic convertObj = JObject.Parse("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
string name = convertObj.Name;
string address = convertObj.Address.City;
The below example can deserialize JSON to a list of anonymous objects using NewtonSoft.Json's DeserializeAnonymousType method.
var json = System.IO.File.ReadAllText(#"C:\TestJSONFiles\yourJSONFile.json");
var fooDefinition = new { FieldName = "", AnotherField = 0 }; // type with fields of string, int
var fooListDefinition = new []{ fooDefinition }.ToList();
var foos = JsonConvert.DeserializeAnonymousType(json, fooListDefinition);
You can use Json.NET's LINQ to JSON API
JObject o = JObject.Parse(jsonString);
string prop = (string)o["prop"];
Use Newtonsoft.Json
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
var json = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb','c':'cc'}]";
var ja = (JArray)JsonConvert.DeserializeObject(json);
var jo = (JObject) ja[0];
Console.WriteLine(jo["a"]);
I had this problem working with unknown APIs then I decide to come over this problem using this approach, I'm writing down here my test case:
[TestMethod]
public void JsonDocumentDeserialize()
{
string jsonResult = #"{
""status"": ""INTERNAL_SERVER_ERROR"",
""timestamp"": ""09-09-2019 11:00:24"",
""message"": ""documentUri is required.""
}";
var jDoc = JsonDocument.Parse(jsonResult);
if (jDoc.RootElement.TryGetProperty("message", out JsonElement message))
{
Assert.IsTrue(message.GetString() == "documentUri is required.");
}
}
it worked for me because first I was looking to find a way to use dynamic type as it's mentioned in Azure Function HTTPTrigger. But I found this approach most useful and robust.
Microsoft Reference
I have a JSON that looks like this:
{
"Identifier1":"TextOfIdentifier1",
"Identifier2":"TextOfIdentifier2",
"Identifier3":"TextOfIdentifier3",
...
}
I know how to deseralize a JSON into a custom object, I followed what says here, but all identifiers appear in the same JSON tag...
How can I get all identifiers inside the JSON?
The solution is like this in my case:
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
JObject jsonLines = JObject.Parse(json);
foreach (var token in jsonLines)
{
dtos.Add(new TokenDto { HalId = token.Key, SourceText = token.Value.ToString() });
}
}
You can traverse JSON (similar to XDocument):
var json = "{\"Identifier1\":\"TextOfIdentifier1\",\"Identifier2\":\"TextOfIdentifier2\",\"Identifier3\":\"TextOfIdentifier3\"}";
foreach (var token in JObject.Parse(json).Children())
Console.WriteLine(token.Path);
Result:
Identifier1
Identifier2
Identifier3
I have an asp.net-mvc website and i am reading in Json string from a Database. Here is the following json in a DB. It could look like this:
{"description": "Test", "contacts": ["joe#gmail.com", "bill#yahoo.com"], "enabled": true}
or this:
{"description": "Test", "contacts": "joe#gmail.com, bill#yahoo.com", "enabled": true}
so as you can see, the contacts field is either:
a string (with items separated by commas)
an array of strings.
I want to convert to this class:
public class MyJob
{
public string description;
public string[] contacts;
public string enabled;
}
when i try to assign just to a string (changing the above to this: public string contacts;
) using the JavascriptSerializer():
var serializer = new JavaScriptSerializer();
string contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
I get this error in the cases where its an array: Type 'System.String' is not supported for deserialization of an array.
what is the best way to go about deserializing this to handle the case of:
a string
an array of strings.
for the contact field. I am happy to put any conditional logic needed . .
I tried this:
var contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
if (contacts is string)
{
jobInfo.contacts = contacts;
}
else
{
jobInfo.contacts = String.Join("; ", contacts );
}
but that didn't seem to fix as i am still getting the error above when its an array
try
var contacts = (new JavaScriptSerializer().DeserializeObject(theAboveJsonString) as Dictionary<string, object>)["contacts"];
if (contacts is object[])
{
jobInfo.contacts = String.Join("; ", contacts as object[]);
}
else
{
jobInfo.contacts = contacts.ToString();
}
For reference see MSDN and here.
You may be interested in some details here: JSON.net - field is either string or List<string>
If you're willing to use Json.NET, have this function:
public string[] getAsArray(JToken token)
{
if (token.HasValues)
{
return token.Select(m => string(m)).ToArray();
}
else
{
return ((string)token).Split(",").Select(s => s.Trim()).ToArray();
}
}
Then usage:
var json = "...";
JObject o = JObject.Parse(json);
string[] contacts = getAsArray(o["contacts"]);
For either JSON the result should be the same.
Try to deserialize contacts into a string array instead of a plain string:
string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts;
if the JSON variable is holding a plain string, use:
string[] contacts = serializer.Deserialize<MyJob>(theAboveJsonString).contacts.Split(',');