C# Newtonsoft cant modify array in JSON file - c#

I have a JSON file from this schema.
This has an array called accounts.
{
"UplayExecutable": "C:\\Program Files (x86)\\Ubisoft\\Ubisoft Game Launcher\\UbisoftConnect.exe",
"foo": "barr",
"OpeningTime": 8,
"accounts": [
"abc#a.com , testpass",
"rumirad#gmail.com , password2",
"rumirad#outlook.com , password3",
"rumirad#test.com , password3"
]
}
I am using .NET framework.I also use the newtonsoft library. I want to replace that array with a C # String array.
The string array is hard-coded because I want to test it here.
This has no compile errors. There is a runtime error.
private void button1_Click(object sender, EventArgs e)
{
string json = File.ReadAllText("data.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jsonObj["accounts"] = accs;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", output);
}
I want to know how to write a string array to a file as a json array
This is the error .I read the newtonsoft documentation but i could not find any solution

your type casting is wrong. Beast way is to use c# object like below.
Create one class for json data
public class jsonData
{
public string UplayExecutable { get; set; }
public string foo { get; set; }
public int OpeningTime { get; set; }
public string[] accounts { get; set; }
}
Now, write code for reading json file, update accounts value and write back to file.
string json = File.ReadAllText("data.json");
var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject<jsonData>(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jsonObj.accounts = accs;
var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", jsonString);

Yes you cannot implicitly cast string[] to a JContainer the way you fix it is by assigning a JArray with string[] values inside., here is a fix to your code
string json = File.ReadAllText("data.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jsonObj["accounts"] = new JArray(accs);
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("data.json", output);
However we dont need to use dynamic typing here, we can just parse the JSON, replace the array then get the json back. like so
string json = File.ReadAllText("data.json");
var jObject = JObject.Parse(json);
string[] accs = { "hi#hi.com , testpass", "hey#hey.com , abcd123", "hello#hello.com , hi123" };
jObject["accounts"] = new JArray(accs);
File.WriteAllText("data.json", jObject.ToString(Newtonsoft.Json.Formatting.Indented) );

Related

.NET 6 “core” Create Dynamic Object containing List<MyOtherDynamicListObject> [duplicate]

For some of my unit tests I want the ability to build up particular JSON values (record albums in this case) that can be used as input for the system under test.
I have the following code:
var jsonObject = new JObject();
jsonObject.Add("Date", DateTime.Now);
jsonObject.Add("Album", "Me Against The World");
jsonObject.Add("Year", 1995);
jsonObject.Add("Artist", "2Pac");
This works fine, but I have never really like the "magic string" syntax and would prefer something closer to the expando-property syntax in JavaScript like this:
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
Well, how about:
dynamic jsonObject = new JObject();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against the world";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
You can use the JObject.Parse operation and simply supply single quote delimited JSON text.
JObject o = JObject.Parse(#"{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}");
This has the nice benefit of actually being JSON and so it reads as JSON.
Or you have test data that is dynamic you can use JObject.FromObject operation and supply a inline object.
JObject o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
Json.net documentation for serialization
Neither dynamic, nor JObject.FromObject solution works when you have JSON properties that are not valid C# variable names e.g. "#odata.etag". I prefer the indexer initializer syntax in my test cases:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = "2Pac"
};
Having separate set of enclosing symbols for initializing JObject and for adding properties to it makes the index initializers more readable than classic object initializers, especially in case of compound JSON objects as below:
JObject jsonObject = new JObject
{
["Date"] = DateTime.Now,
["Album"] = "Me Against The World",
["Year"] = 1995,
["Artist"] = new JObject
{
["Name"] = "2Pac",
["Age"] = 28
}
};
With object initializer syntax, the above initialization would be:
JObject jsonObject = new JObject
{
{ "Date", DateTime.Now },
{ "Album", "Me Against The World" },
{ "Year", 1995 },
{ "Artist", new JObject
{
{ "Name", "2Pac" },
{ "Age", 28 }
}
}
};
There are some environment where you cannot use dynamic (e.g. Xamarin.iOS) or cases in where you just look for an alternative to the previous valid answers.
In these cases you can do:
using Newtonsoft.Json.Linq;
JObject jsonObject =
new JObject(
new JProperty("Date", DateTime.Now),
new JProperty("Album", "Me Against The World"),
new JProperty("Year", "James 2Pac-King's blog."),
new JProperty("Artist", "2Pac")
)
More documentation here:
http://www.newtonsoft.com/json/help/html/CreatingLINQtoJSON.htm
Sooner or later you will have property with a special character. e.g. Create-Date. The hyphen won't be allowed in property name. This will break your code. In such scenario, You can either use index or combination of index and property.
dynamic jsonObject = new JObject();
jsonObject["Create-Date"] = DateTime.Now; //<-Index use
jsonObject.Album = "Me Against the world"; //<- Property use
jsonObject["Create-Year"] = 1995; //<-Index use
jsonObject.Artist = "2Pac"; //<-Property use
Simple way of creating newtonsoft JObject from Properties.
This is a Sample User Properties
public class User
{
public string Name;
public string MobileNo;
public string Address;
}
and i want this property in newtonsoft JObject is:
JObject obj = JObject.FromObject(new User()
{
Name = "Manjunath",
MobileNo = "9876543210",
Address = "Mumbai, Maharashtra, India",
});
Output will be like this:
{"Name":"Manjunath","MobileNo":"9876543210","Address":"Mumbai, Maharashtra, India"}
May I suggest using the nameof expression combined with a model for the structure you're trying to build?
Example:
record RecordAlbum(string Album, string Artist, int Year);
var jsonObject = new JObject
{
{ nameof(RecordAlbum.Album), "Me Against The World" },
{ nameof(RecordAlbum.Artist), "2Pac" },
{ nameof(RecordAlbum.Year), 1995 }
};
As an added benefit to removing the "magic string" aspect - this also will give you a little bit of refactor-ability. You can easily rename any given property name for the record and it should update the value returned by the nameof() expression.
You can use Newtonsoft library and use it as follows
using Newtonsoft.Json;
public class jb
{
public DateTime Date { set; get; }
public string Artist { set; get; }
public int Year { set; get; }
public string album { set; get; }
}
var jsonObject = new jb();
jsonObject.Date = DateTime.Now;
jsonObject.Album = "Me Against The World";
jsonObject.Year = 1995;
jsonObject.Artist = "2Pac";
System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
new System.Web.Script.Serialization.JavaScriptSerializer();
string sJSON = oSerializer.Serialize(jsonObject );

c# Json get value from list sourced from usgs url

I need help extracting and returning values from json as either doubles or string, either should be fine.
The URL being used it: <https://earthquake.usgs.gov/ws/designmaps/asce7-16.json?latitude=34&longitude=-118&riskCategory=III&siteClass=C&title=Example>
here is the json
{
"request": {
"date": "2021-01-30T19:07:52.176Z",
"referenceDocument": "ASCE7-16",
"status": "success",
"url": "https://earthquake.usgs.gov/ws/designmaps/asce7-16.json?latitude=34&longitude=-118&riskCategory=III&siteClass=C&title=Example",
"parameters": {
"latitude": 34,
"longitude": -118,
"riskCategory": "III",
"siteClass": "C",
"title": "Example"
}
},
"response": {
"data": {
"pgauh": 0.819,
"pgad": 1.021,
"pga": 0.819,
"fpga": 1.2,
"pgam": 0.983,
"ssrt": 1.888,
"crs": 0.896,
"ssuh": 2.106,
"ssd": 2.432,
"ss": 1.888,
"fa": 1.2,
"sms": 2.265,
"sds": 1.51,
"sdcs": "D",
"s1rt": 0.669,
"cr1": 0.9,
"s1uh": 0.743,
"s1d": 0.963,
"s1": 0.669,
"fv": 1.4,
"sm1": 0.936,
"sd1": 0.624,
"sdc1": "D",
"sdc": "D",
"tl": 8,
"t-sub-l": 8,
"cv": 1.278,
...
url is defined as an input and Ss and S1 are defined as outputs per VisualStudio 2019 grasshopper developer C# template.
right now Ss and S1 return null values, they should return 1.888 and 0.669, respectively.
using Grasshopper.Kernel;
using System;
using System.Net;
using Newtonsoft.Json.Linq;
protected override void SolveInstance(IGH_DataAccess DA)
{
string url = "";
DA.GetData(0, ref url);
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString(url);
JObject jObj = JObject.Parse(json); // Parse the object graph
string Ss = (string)jObj["ss"];
string S1 = (string)jObj["s1"];
//Functions I also tried
//var data = jObj["data"];
//foreach (var d in data) ;
//var Ss = d["ss"];
//double Ss = jObj.GetValue("ss").ToObject<double>();
//string Ss = jObj.GetValue("ss").Value<string>();
//string Ss = jObj.GetValue("ss").ToString();
//string Ss = jObj["ss"].ToString();
DA.SetData(0, Ss);
DA.SetData(1, S1);
}
}
The information you are looking for is nested in two levels, you have to access the response object then the data object, this should work:
var json = wc.DownloadString(url);
JObject jObj = JObject.Parse(json); // Parse the object graph
var data = jObj["response"]["data"];
var ss = data["ss"].ToObject<double>(); // or .ToString() if you want the string value
var s1 = data["s1"].ToObject<double>(); // or .ToString() if you want the string value
DA.SetData(0, ss);
DA.SetData(1, s1);
note: this code lacks null checks and error handling (try-catch block) for the sake of simplicity. But you need to add that in your code.
your data is null, is because your need Deserilize Json
using httpclientFactory
var httpclient = _httpClientFactory.CreateClient();
var responseDatas = await httpclient.GetAsync("https://earthquake.usgs.gov/ws/designmaps/asce7-16.json?latitude=34&longitude=-118&riskCategory=III&siteClass=C&title=Example");
if (responseDatas.IsSuccessStatusCode)
{
var responseDatasJson = await responseDatas .Content.ReadAsStringAsync();
var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
var resultDataJson = JsonSerializer.Deserialize<Root>(responseDatasJson, options);
return (resultDataJson);
}
for convert json to c# class use this site Json to c# class
or use visual studio options
Edit-->Paste Special-->Paste Json As Classes
public class Data {
public double ss{ get; set; }
public double s1{ get; set; }
....your properties
}
public class Response {
public Data data { get; set; }
}
public class Root {
public Response response { get; set; }
}

JSON Serialize array returns NULL in JSON string

I am building a JSON model like this
JObject issue_model = JObject.FromObject(new
{
labels = new[] { "import", "automation"}
}
below code for serialization
string request_json = JsonConvert.SerializeObject(issue_model,
Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
But when i try to build this from a dynamic list of values like
list<string> lp_list = new list<string>();
//lp_list contains a list of string values
string[] lp_labels = lp_list.ToArray();
JObject issue_model = JObject.FromObject(new
{
labels = jira_labels
}
I got the JSON as
"labels": [
[
null,
null
]
]
But i am expecting this json as
"labels" : { "import", "automation"}
How can i make the array serialization right way
I modified your code in a console Application.
List<string> lp_list = new List<string>();
lp_list.Add("import");
lp_list.Add("automation");
//lp_list contains a list of string values
//string[] lp_labels = lp_list.ToArray();
JObject issue_model = JObject.FromObject(new
{
labels = lp_list
});
Console.WriteLine(issue_model);
The result is as follows:
Hope it answers your question.

JSON DeserializeObject Error converting value

I am getting 'Error converting value' when I try to use deserilizeobject. My client sometimes sends data with quotes and special characters in it. It works when they try to serialize it. But it doesn't work when I try to deserilize it. I tried with escapehtml but still I have the same issue. It looks like 'SerializeObject' is not throwing error message that means it's valid JSON. Please let me know how to solve this issue.
string json2 = #"{
'RootObject1':{
't_date': '03-JAN-2016',
't_summary': 'test """"""""""""'
}
}";
var json3 = JsonConvert.SerializeObject(json2, Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings{ StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml });
var myJsonObject = JsonConvert.DeserializeObject<RootObject1>(json3);
class RootObject1
{
public string t_date { get; set; }
public string t_summary { get; set; }
}
This is not the correct way how you should use JsonConvert.Serialize and Deserialize.
At the beginning you should Serialize the object to string and then Deserialize back from string to object. Here is example of that:
RootObject1 ro = new RootObject1();
ro.t_date = "03-JAN-2016";
ro.t_summary = #"test """"""""""""";
var json3 = JsonConvert.SerializeObject(ro, typeof(RootObject1), Newtonsoft.Json.Formatting.None, new Newtonsoft.Json.JsonSerializerSettings { StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml });
var myJsonObject = JsonConvert.DeserializeObject<RootObject1>(json3);
Console.WriteLine(myJsonObject.t_date + "\t" + myJsonObject.t_summary);
When you are trying to Serialize string then it will be Deserialze to string also. And it has no meaning at some point to do that.
Also if you want to get the object from JSON string you should do Deserealization and your JSON string is not valid. Here is example how you can achieve that:
string json2 = #"{
't_date': '03-JAN-2016',
't_summary': 'test """"""""""""'
}";
var obj = JsonConvert.DeserializeObject<RootObject1>(json2);
Console.WriteLine(obj.t_date + "\t" + obj.t_summary);

converting array of string to json object in C#

I have got following scenario where i have a array of strings and i need to pass this data as json object.
How can I convert array of string to json object using DataContractJsonSerializer.
code is :
string[] request = new String[2];
string[1] = "Name";
string[2] = "Occupaonti";
I would recommend using the Newtonsoft.Json NuGet package, as it makes handling JSON trivial. You could do the following:
var request = new String[2];
request[0] = "Name";
request[1] = "Occupaonti";
var json = JsonConvert.SerializeObject(request);
Which would produce:
["Name","Occupaonti"]
Notice that in your post you originally were trying to index into the string type, and also would have received an IndexOutOfBounds exception since indexing is zero-based. I assume you will need values assigned to the Name and Occupancy, so I would change this slightly:
var name = "Pooja Kuntal";
var occupancy = "Software Engineer";
var person = new
{
Name = name,
Occupancy = occupancy
};
var json = JsonConvert.SerializeObject(person);
Which would produce:
{
"Name": "Pooja Kuntal",
"Occupancy": "Software Engineer"
}
Here's a simple class that should do the job. I took the liberty of using Newtonsoft.Json instead of DataContractJsonSerializer.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] request = new String[2];
request[0] = "Name";
request[1] = "Occupaonti";
string json = JsonConvert.SerializeObject(request);
}
}
}

Categories