I have a JObject like this:
{
"#STARTDATE": "'2016-02-17 00:00:00.000'",
"#ENDDATE": "'2016-02-18 23:59:00.000'"
}
I want to get #STARTDATE and #ENDDATE value from JObject.
This is a sample code that I've tried to do the task:
JObject json = JObject.Parse("{\"#STARTDATE\": \"'2016-02-17 00:00:00.000'\",\"#ENDDATE\": \"'2016-02-18 23:59:00.000'\"}");
var key = "#STARTDATE";
var value = GetJArrayValue(json, key);
private string GetJArrayValue(JObject yourJArray, JToken key)
{
string value = "";
foreach (JToken item in yourJArray.Children())
{
var itemProperties = item.Children<JProperty>();
//If the property name is equal to key, we get the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == key.ToString());
value = myElement.Value.ToString(); //It run into an exception here because myElement is null
break;
}
return value;
}
Note: The code above cannot get the value by key from JObject.
Could you help me to find a way to get the value by key from JObject?
This should help -
var json = "{'#STARTDATE': '2016-02-17 00:00:00.000', '#ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["#STARTDATE"];
You can also get the value of an item in the jObject like this:
JToken value;
if (json.TryGetValue(key, out value))
{
DoSomething(value);
}
Try this:
private string GetJArrayValue(JObject yourJArray, string key)
{
foreach (KeyValuePair<string, JToken> keyValuePair in yourJArray)
{
if (key == keyValuePair.Key)
{
return keyValuePair.Value.ToString();
}
}
}
Related
I have struggled to finish this task, please if anyone can give me a hint I would be so thankful.
My main task is to get data from database using (FOR JSON AUTO) which is working :)
select filed1, field2, field3 from table FOR JSON AUTO;
And then after connecting to Data base I use the StringBuilder() to build a Json Array of objects which is working :)
var jsonResult = new StringBuilder();
if(!r.HasRows)
{
jsonResult.Append("[]");
}
else
{
while(r.Read())
{
jsonResult.Append(r.GetValue(0).ToString());
}
// JArray array = JArray...
}
After that I am trying to change the value of filed1 for each object inside the Json Array
JArray array = JArray.Parse(jsonResult.ToString());
foreach (JObject obj in array.Children<JObject>())
{
foreach (JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
if(name.ToString() == "field1")
{
Int64 newID = 1234;
value = newID.ToString();
}
}
}
This is working but My BIG QUESTION is how can I get it changed inside the jsonResult?
You simply have to replace the value that you want to update. Since StringBuilder has a .Replace inbuilt method, you can implement that method.
`JArray arr = JArray.Parse(jsonResult.ToString());
foreach (JObject obj in arr.Children<JObject>())
{
foreach(JProperty singleProp in obj.Properties())
{
string name = singleProp.Name;
string value = singleProp.Value.ToString();
if (name.ToString().Equals("field1")) //good practice
{
Int64 newID = 1234;
jsonResult.Replace(value, newID.ToString());//replacing old value with new value and directly updates jsonResult
}
//not necesssary, explanation is given below
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonResult.ToString());
result = JsonSerializer.Serialize(jsonElement, options);
}
}`
And for better formatting, I used JsonSerializer so that your output will look like json object rather than whole string without any lines.
` var options = new JsonSerializerOptions()
{
WriteIndented = true
};
var result = ""
while loop{
jsonResult.Append(r.GetValue(0).ToString());
(Above code)
}
`
I'm able to get a dynamic Json object using
dynamic obj = JsonConvert.DeserializeObject(json);
It seems to be a nested object structure
I need to graph every variable in the json file, but the json file structure changes often
Is there a way to parse through this structure using nested foreach() statements?
If not, can can I parse it by accessing each element via a string like a Dictionary?
for example something like:
if(obj["Item1"]["Parameter3"]["Value2"]` != NULL)
int number = obj["Item1"]["Parameter3"]["Value2"]`
Thanks,
Yes there is an API for querying dynamically.
See the documentation here: https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm
Code looks something like this:
JObject rss = JObject.Parse(json);
var postTitles =
from p in rss["channel"]["item"]
select (string)p["title"];
Finally figured this api out
Some JToken entries have a list of values, others have a name and value. You have to sort which one is which prior to parsing it.
This will create a Dictionary with every entry in the Json file
void SomeFunction()
{
Dictionary<string, decimal> json_data = new Dictionary<string, decimal>();
dynamic json_obj = JsonConvert.DeserializeObject(json);
Linearize(ref json_data, json_obj);
}
void Linearize(ref Dictionary<string, decimal> input_dict, JToken json_data, string key = "")
{
int i;
if (json_data != null)
{
if (json_data.HasValues)
{
i = 0;
foreach (dynamic entry in json_data)
{
//Add a Name field if it exists
Type typeOfDynamic = entry.GetType();
if (typeOfDynamic.GetProperties().Where(p => p.Name.Equals("Name")).Any())
key += entry.Name + ".";
//If JToken is an Array
if (((JToken)entry).HasValues)
{
Linearize(ref input_dict, entry, key + "[" + i++ + "]" + ".");
}
//If JToken is a data type
else if (entry.Type == JTokenType.String || entry.Type == JTokenType.Float || entry.Type == JTokenType.Integer)
{
decimal output;
if (decimal.TryParse(entry.ToString(), out output))
input_dict.Add(key + "[" + i++ + "]", output);
}
}
}
}
}
I have below json in string as parameter to a WebMethod.
How can I deserialize in such a way that value comes in Key value pair.
Json String Parameter:
["Ref No,0","Date,0","Amt,0","Sender Name,0","Sender Add,0","Beneficiary Name,0","Beneficiary Add,0","Phone,0","Secret Code,0","Secret Ans,0","Preferred Id,0"]
WebMethod:
[System.Web.Services.WebMethod]
public static string SaveMappings(string mappingData)
{
//string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\"}";
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//object obj;
//var data = serializer.Deserialize(mappingData,);
var data = mappingData.ToArray();
if (data != null)
{
}
var d2 = mappingData.Split(',');
if (d2!=null)
{
}
return mappingData;
}
If you need to work with JSON data then use Newtonsoft.JSON library.
Convert the object to an array of strings and then split every line.
With this approach you can be sure that the given string is actually an JSON array and it is correct.
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
string[] objs = JsonConvert.DeserializeObject<string[]>(str);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (var obj in objs)
{
var keyValue = obj.Split(',');
dic.Add(keyValue[0], keyValue[1]);
}
foreach (var record in dic)
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
Or this one using LINQ. It looks better and it can be written faster. However, it is less optimal (two calls of Split instead of one).
public Dictionary<string, string> FromJsonArray(string jsonArray)
{
return JsonConvert.DeserializeObject<string[]>(jsonArray)
.ToDictionary(obj => obj.Split(',')[0], obj => obj.Split(',')[1]);
}
// ...
var str = "[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]";
foreach (var record in FromJsonArray(str))
{
Console.WriteLine("{0} => {1}", record.Key, record.Value);
}
why don't you just change every ',' in the string array to ':' then pass it to the method, from what you wrote in the question, this should work
Hi there I have json that looks like this:
{
"Id": " 357342524563456678",
"title": "Person",
"language": "eng",
"questionAnswer": [
{
"4534538254745646.1": {
"firstName": "Janet",
"questionNumber": "1.1"
}
}
]
}
Now I have written some code that loops over the objects in the questionAnswer array and then gets the name of the object which is 4534538254745646.1. Now Im trying to save the key of each Item and the value aswell but I am only managing to get the value.
How would I do this, here is my code:
JToken entireJson = JToken.Parse(json);
JArray inner = entireJson["questionAnswer"].Value<JArray>();
foreach(var item in inner)
{
JProperty questionAnswerDetails = item.First.Value<JProperty>();
//This line gets the name, which is fine
var questionAnswerSchemaReference = questionAnswerDetails.Name;
var properties = questionAnswerDetails.Value.First;
//This only gets Janet
var key = properties.First;
var value = properties.Last;
}
So at the moment Im only able to get Janet, But I also want the firstname field. I want to then take this and add to a dictionary i.e.
Dictionary<string, string> details = new Dictionary<string, string>();
//suedo
foreach(var item in questionAnswerObjects)
details.Add(firstName, Janet);
//And then any other things found below this
So Here is he complete code that gets the keys and values for each item in the object in the array:
string key = null;
string value = null;
foreach(var item in inner)
{
JProperty questionAnswerDetails = item.First.Value<JProperty>();
var questionAnswerSchemaReference = questionAnswerDetails.Name;
var propertyList = (JObject)item[questionAnswerSchemaReference];
questionDetails = new Dictionary<string, object>();
foreach (var property in propertyList)
{
key = property.Key;
value = property.Value.ToString();
}
questionDetails.Add(key, value);
}
I can now add key and value to the dictionary
How could you convert a string of JSON to a C# NameValueCollection simply, preferably without using a 3rd party parser?
I'm not sure why everyone is still recommending JSON.NET for deserialization of JSON. I wrote a blog post on how to deserialize JSON to C#.
In short, it's like this:
using System.Web.Script.Serialization;
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, string>>(jsonText);
NameValueCollection nvc = null;
if (dict != null) {
nvc = new NameValueCollection(dict.Count);
foreach (var k in dict) {
nvc.Add(k.Key, k.Value);
}
}
}
var json = jss.Serialize(dict);
Console.WriteLine(json);
Be sure to add a reference to System.Web.Extensions.dll.
Note:
I usually deserialize to dynamic, so I'm assuming that NameValueCollection would work. However, I haven't verified if it actually does.
EDIT
Pure .net solution without third party development have look : JavaScriptSerializer – Dictionary to JSON Serialization and Deserialization
make use of Json.NET
string jsonstring = #"{""keyabc"":""valueabc"",""keyxyz"":""valuexyz""}";
Dictionary<string, string> values =
JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonstring);
Check #jon answer suggest same : .Net Linq to JSON with Newtonsoft JSON library
If your JSON contains nested objects whithin it the solution below will handle them properly (based on JSON.NET, but you can adapt to the JSON parser of your choice).
This usage example:
var json = "{\"status\":\"paid\",\"date\":\"2019-10-09T17:30:51.479Z\",\"customer\":{\"id\":123456789,\"country\":\"br\",\"name\":\"Thomas Vilhena\",\"phone_numbers\":[\"+5511987654321\"],\"documents\":[{\"id\":\"doc_id\"}]}}";
var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
var nvc = new NameValueCollection(dict.Count);
AddKeyValuePairs(nvc, dict);
Console.WriteLine(nvc["status"]);
Console.WriteLine(nvc["date"]);
Console.WriteLine(nvc["customer[phone_numbers][0]"]);
Console.WriteLine(nvc["customer[id]"]);
Console.WriteLine(nvc["customer[documents][0][id]"]);
Produces the following output:
paid
09.10.2019 17:30
+5511987654321
123456789
doc_id
And here's the implementation:
private static void AddKeyValuePairs(
NameValueCollection nvc,
Dictionary<string, object> dict,
string prefix = null)
{
foreach (var k in dict)
{
var key = prefix == null ? k.Key : prefix + "[" + k.Key + "]";
if (k.Value != null)
AddKeyValuePair(nvc, key, k.Value);
}
}
private static void AddKeyValuePair(
NameValueCollection nvc,
string key,
object value)
{
if (value is string || value.GetType().IsPrimitive)
{
nvc.Add(key, value.ToString());
}
else if (value is DateTime)
{
nvc.Add(key, ((DateTime)value).ToString("g"));
}
else
{
AddNonPrimitiveValue(nvc, key, value);
}
}
private static void AddNonPrimitiveValue(
NameValueCollection nvc,
string key,
object value)
{
var a = value as JArray;
if (a != null)
{
for (int i = 0; i < a.Count; i++)
AddKeyValuePair(nvc, key + "[" + i + "]", a[i]);
}
else
{
var v = value as JValue;
if (v != null)
{
AddKeyValuePair(nvc, key, v.Value);
}
else
{
var j = value as JObject;
if (j != null)
AddKeyValuePairs(nvc, j.ToObject<Dictionary<string, object>>(), key);
}
}
}