I am trying to serialize an object with Newtonsoft Json converter like this:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
string json = new Newtonsoft.Json.JsonConvert.SerializeObject(new
{
jlpt = "5"
});
but it gives me an error saying that
SerializeObject does not exist.
However, when I click to check the reference I see it.
Can anyone point me to what I am doing wrong?
Remove new instance creation of Newtonsoft.Json.JsonConvert, because SerializeObject is a static method you don't need create a instance of the Newtonsoft.Json.JsonConvert to use it
string json = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
jlpt = "5"
});
also if you add using Newtonsoft.Json; to the program then you simply use like this
string json = JsonConvert.SerializeObject(new
{
jlpt = "5"
});
Related
I am working on a method to asynchronously read the contents of a json file ( containing an array of json objects) and insert it into a mongodb collection but I cannot figure out what the issue is. There is no error when debugging, but my collection is still empty.
public async void InsertDocumentsInCollection(string File)
{
string text = System.IO.File.ReadAllText(File);
IEnumerable<BsonDocument> doc = BsonSerializer.Deserialize<BsonArray>(text).Select(p => p.AsBsonDocument);
//Name of the collection is Cars
var collection = _database.GetCollection<BsonDocument>("Cars");
await collection.InsertManyAsync(doc);
}
i tried to reproduce the issue with the following, but it works just fine. maybe it's something wrong with the contents of the text file. can you post a sample of the file?
using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace StackOverflow
{
public class Program
{
private static async Task Main(string[] args)
{
var content = File.ReadAllText("E:\\Downloads\\cars.txt"); //https://mongoplayground.net/p/LY0W7vjDuvp
var docs = BsonSerializer.Deserialize<BsonArray>(content).Select(p => p.AsBsonDocument);
var collection = new MongoClient("mongodb://localhost")
.GetDatabase("test")
.GetCollection<BsonDocument>("Cars");
await collection.InsertManyAsync(docs);
}
}
}
I'm following a guide to write output data from Visual Studio into a google spreadsheet.
At the end of the guide there is a code block that I pasted inside my project:
using OpenQA.Selenium.Support.UI;
using System;
using NUnit.Framework;
using OpenQA.Selenium;
using System.Collections;
using System.Collections.Generic;
using Google.Apis.Sheets.v4;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Services;
using Newtonsoft.Json;
using WikipediaTests.Foundation_Class;
using System.Web;
using System.Data;
using Google.Apis.Sheets.v4.Data;
namespace AutomationProjects
{
[TestFixture]
public class TestClass : TestFoundation
{
public class SpreadSheetConnector
{
//Codeblock from guide pasted here!
}
[Test]
public void test1()
{
//Test case 1. Do XYZ...
}
}
}
In the code block included in the guide there is a section about creating a list and passing data into it:
// Pass in your data as a list of a list (2-D lists are equivalent to the 2-D spreadsheet structure)
public string UpdateData(List<IList<object>> data)
{
String range = "My Tab Name!A1:Y";
string valueInputOption = "USER_ENTERED";
// The new values to apply to the spreadsheet.
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
var dataValueRange = new Data.ValueRange();
dataValueRange.Range = range;
dataValueRange.Values = data;
updateData.Add(dataValueRange);
Data.BatchUpdateValuesRequest requestBody = new Data.BatchUpdateValuesRequest();
requestBody.ValueInputOption = valueInputOption;
requestBody.Data = updateData;
var request = _sheetsService.Spreadsheets.Values.BatchUpdate(requestBody, _spreadsheetId);
Data.BatchUpdateValuesResponse response = request.Execute();
// Data.BatchUpdateValuesResponse response = await request.ExecuteAsync(); // For async
return JsonConvert.SerializeObject(response);
}
The problem is that I get an error for the 'Data.ValueRange' and the 'Data.BatchUpdateValuesRequest' :
CS0246 The type or namespace name 'Data' could not be found (are you missing a using directive or an assembly reference?)
I tried adding "System.Data" as a assembly reference to my project and then added it at the top (using). But it did not remove the error.
'Data.' seems to belong to "Google.Apis.Sheets.v4" but I have already added that reference as the guide instructed.
The only fix that gets rid of the error is adding Google.Apis.Sheets.v4 before every 'Data.' like this:
List<Google.Apis.Sheets.v4.Data.ValueRange>
But when I run my tests the output does not get exported to my spreadsheet. So I'm assuming this is not the correct solution. And also I'm assuming that the guide should have included this in the code block if it was necessary.
Could there be some other reference about 'Data' I need?
According to the documentation, the ValueRange Class depends of Sheets.v4.Data, so you should add:
using Google.Apis.Sheets.v4.Data;
Also, change:
List<Data.ValueRange> updateData = new List<Data.ValueRange>();
to:
List<ValueRange> updateData = new List<ValueRange>();
I need to pass a variable from C# to javascript in the form { 'key':'value', ..., }. I tried passing it as a string and hoping javascript would parse it (because the C# on cshtml pages is evaluated server side and js is client side) but unfortunately the quotes were formatted as &whateverthecodeis; so it didn't work. I think JSON might be what I'm looking for, but I have no idea how to use it.
Here is what I might do...
Run this console app and see what it does:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// note: you will have to include a reference to "System.Web.Extensions" in your project to be able to use this...
using System.Web.Script.Serialization;
namespace KeyValuePairTestApp
{
class Program
{
static void Main(string[] args)
{
List<KeyValuePair<string, string>> pairs = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("MyFirstKey", "MyFirstValue"),
new KeyValuePair<string, string>("MySecondKey", "MySecondValue")
};
string json = new JavaScriptSerializer().Serialize(pairs);
Console.WriteLine(json);
}
}
}
For the "pass to javascript" part, please see here Making a Simple Ajax call to controller in asp.net mvc for practical examples for MVC and jQuery.
Yes you can use JSON.
Perhaps you should try using escape characters to escape the quotes being misinterpreted.
Or as in the above answer #user1477388, serialize the keyvalupairs to Json and return as following:
public ActionResult ReturnJsonObject()
{
//Your code goes here
return Json(json);
}
Below is what I use to log into the database using linq and then I use C# expressions to gather the data I want. The next thing I want to do is convert this data into an XML any Ideas?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Data;
namespace VcacManagementTools.BuildProfiles
{
public static class BuildProfileTools
{
public static ICollection<string> GetExistingBuildProfileNames(string repositoryHostname,
string repositoryUsername,
string repositoryPassword)
{
var url = string.Format("https://{0}/repository/data/ManagementModelEntiti.svc", repositoryHostname);
var managementModelClient = new DynamicOps.ManagementModel.ManagementModelEntities(new Uri(url))
{
Credentials = new NetworkCredential(repositoryUsername, repositoryPassword)
};
return managementModelClient
.GlobalProfiles
.Select(gp => gp.ProfileName)
.ToList();
The Output I recieve is a list of values
If I understood you well, you want to take the data (the list contains the data from the database) and put it in XML file. I used variables to show where to put each data.
In case you have an XML:
try
{
doc = XDocument.Load(spath, LoadOptions.SetBaseUri);
foreach(String propertyData in dataList)
{
XElement root = new XElement(ElementName);
root.Add(new XElement("property1", propertyData));
doc.Element(MainElement).Add(root);
}
doc.Save(spath);
}
catch (Exception)
{
}
How do i print out a selected field from my json object without having to create classes for it, at the moment it prints out the whole json object but i just want to print out selected fields for example something like Console.WriteLine(response.venues.name);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace FourSquareTest
{
class Program
{
static void Main(string[] args)
{
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString("https://api.foursquare.com/v2/venues/search?ll=40.7,-74&query=mcdonalds&client_id=XXXXXXX&client_secret=XXXXXXXX&v=20120101");
// Now parse with JSON.Net
JObject parsed = JObject.Parse(json);
foreach (var pair in parsed)
{
Console.WriteLine("{0}: {1}", pair.Key, pair.Value);
}
}
}
}
}
Try
JObject parsed = JObject.Parse(json);
JToken response = parsed["response"];
JArray venues = (JArray)response["venues"];
JValue names = (JValue)venues[1]["name"];
But I don't have the library to test, so that's just based on the documentation.