How to Convert C# Values to Node.js Object - c#

I have simple C# object instantiated like
User theUser = new User("John", "Doe");
now I need to load it to my Node.js file like:
var theUser = {name:"John", lastName:"Doe"};
Can you please let me know how to do that? Do I have to save/write the output on a separate json file? or..?
Thanks

If you intend to use JSON as bridge from C# to Nodejs, use JavaScriptSerializer class to convert your C# class as JSON data.
https://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
C#
// your data class
public class YourClassName
{
...
}
// Javascript serialization
using System.IO;
using System.Web.Script.Serialization;
String json = new JavaScriptSerializer().Serialize(YourClassName);
File.WriteAllText("json_file_path", json);
Node.js
// Async mode
var jsondata = require('fs').readFile('json_file_path', 'utf8', function (err, data) {
if (err) throw err; // throw error if not found or invalid
var obj = JSON.parse(jsondata);
});
// Sync mode
var jsondata = JSON.parse(require('fs').readFileSync('json_file_path', 'utf8'));
Node.js reference: How to parse JSON using Node.js?
Hopefully this is useful, CMIIW.

Why not just use Newtonsoft.Json - add a reference to this within your project.
To convert the object from a known type to json string;
string output = JsonConvert.SerializeObject(theUser);
To convert the object to a dynamic type;
dynamic json = JToken.Parse(theUser); - to dynamic
MSDN Link for extra help, if needed.

Related

Parsing Json information from a Json file as a string

I am looking for some help with regards to Parsing the the value "mppdemo" in the below json file (See screenshot)
{
"client":{
"isWebLogin":false,
"registryName": "mpdemo",
"walletCode": "Local"
}
}
I have done some research in and arround the webs but alot of the examples wither are out dated or dont work.
This is what i have tried
//JObject T = JObject.Parse(File.ReadAllText(DownloadConfigFilelocation));
var source = File.ReadAllText(DownloadConfigFilelocation);
var JavaScriptSerializer MySerializer = new JavaScriptSerializer();
var myObj = MySerializer.Deserialize<T>(source);
var RegistryName = myObj.searchResults[0].hotelID;
MessageBox.Show(RegistryName);
The above doesnt pick up the JavaScriptSerializer function from the library even though im using the using System.Web.Script.Serialization;
Can someone help me get this code segment to work
I hope i have provided enough info
EDIT: I just realized that you're having another problem - that your compiler does not recognize the System.Web.Script.Serialization.JavaScriptSerializer type. You'll need to add a reference to System.Web.Extensions.dll to your project. I don't know what IDE you are using, but for example in SharpDevelop you can right click References > Add Reference > in filter start typing "System.Web.Extensions" > among results find "System.Web.Extensions" and double click it (it will be moved to lower window) > hit OK and compile your project.
If you still want to use System.Web.Script.Serialization.JavaScriptSerializer, I'd probably do it like this:
using System;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
namespace jsonhratky
{
public static class Program {
public static void Main(string[] args)
{
var instance = new JsonParsingTest();
}
}
public class JsonParsingTest
{
class Response {
public Client client;
}
class Client {
public bool isWebLogin;
public string registryName;
public string walletCode;
}
const string JSON_EXAMPLE = ("{" + ("\"client\":{" + ("\"isWebLogin\":false," + ("\"registryName\": \"mpdemo\"," + ("\"walletCode\": \"Local\"" + ("}" + "}"))))));
public JsonParsingTest() {
// Solution #1 using JavaScriptSerializer
var serializer = new JavaScriptSerializer();
Response parsed = serializer.Deserialize<Response>(JSON_EXAMPLE);
Console.WriteLine("parsed isWebLogin: " + parsed.client.isWebLogin);
Console.WriteLine("parsed registryName: " + parsed.client.registryName);
Console.WriteLine("parsed walletCode: " + parsed.client.walletCode);
// Solution #2 (not recommended)
var matches = Regex.Match(JSON_EXAMPLE, "registryName\":.*?\"([^\"]+)\"", RegexOptions.Multiline);
if (matches.Success) {
Console.WriteLine("registryName parsed using Regex: " + matches.Groups[1].Value);
} else {
Console.WriteLine("Solution using Regex failed.");
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
}
You need to create a "POJO" class (there's probably another term in C# for plain old classes) with fields matching those in your string response. Since your fields isWebLogin, registryName and walletCode are not directly part of main object (Response) but they belong to sub-class (Client), you need two classes: Response (or call it whatever you want) and then the field "client" must match string in response (as well as the fields of the sub-class).
Result:
Anyway, I also included a solution using Regex, but I absolutely don't recommend that. It's suitable only as a workaround and only then if you know that your response will never contain more than one "client" objects.
The problem seems to be in this line of your code var myObj = MySerializer.Deserialize<T>(source); You need to give the type of object instead of T.

How to use json methods inside lua script and execute lua script with c#?

I am trying to encode and decode json using lua using c#.I am using NLUA for executing lua script.
I am using Json.Lua file for json manupulation(encode and decode method) but i am not getting how to make it work with nlua in c#.
code :
static void Main(string[] args)
{
Lua state = new Lua();
var jsonConcate = #"[{ ""firstName"":""John"" , ""lastName"":""Doe"", ""email"":""NHP#123.COM"" },{ ""firstName"":""Anna"", ""lastName"":""Smith"", ""email"":""ASD#123.COM"" },{ ""firstName"":""Peter"" , ""lastName"":""Jones"", ""email"":""ZXC#123.COM""}]";
state.DoString(#"
function ScriptFunc (input)
local json = require('json')
local JSON_string = input
return JSON_string end"
);
var scriptFunc = state["ScriptFunc"] as LuaFunction;
var res = scriptFunc.Call(jsonConcate);//Error here
}
This line var res = scriptFunc.Call(jsonConcate) is throwing error :
When i remove this line local json = require('json') then it is working fine.
I have install lua using this installer also :https://github.com/rjpcomputing/luaforwindows
Project : https://www.dropbox.com/s/hbf04d8kqpenzm0/LuaTest.zip?dl=0
Can anybody please help me this?

Convert json file into string

I'm trying to capture the names and values of all nodes coming from a random Json file that I don't know its structure (uploaded by the user).
I can loop through a json string and get the info I need but how do I start from a file? If I want to deserialize it I believe I need a class to hold that data (and I don't know the file structure).
Here's how I loop through elements from a json string:
string json = #"{
'CPU': 'Intel',
'PSU': '500W',
'Drives': [
'DVD read/writer'
/*(broken)*/,
'500 gigabyte hard drive',
'200 gigabype hard drive'
]
}";
JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
{
if (reader.Value != null)
{
Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
}
else
{
Console.WriteLine("Token: {0}", reader.TokenType);
}
}
How do I read from a file and set it as a string that can be handled by the code above? It sounds like a basic question but I'm still struggling with this after several hours. All I've seen expects that you know the structure of the Json file and I don't in this case.
This is the exact use case that dynamic and ExpandoObject were made for! Here you can deserialize the JSON to an object, then traverse the object's properties (look up online how to work with ExpandoObjects).
var expandoConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expandoConverter);
Or, if you were just looking to read the json from disk as a string, then use string json = File.ReadAllText(filePathAndName);
The above code snippet requires installing the package NewtonSoft.
Eriks answer was great to mention the ExpandoObject, dynamic and File call. It got my +1.
I'm adding to ErikEs answer to include the package and include details required for a minimal running program.
This code was in my Program.cs file for a Console App project type in Visual Studio 2017. You should also run install-package newtonsoft.json in the Package Manager Console. This command will load newtonsoft.json.11.0.1 pakcage. .Net Framework was 4.6.1.
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Dynamic;
using System.IO;
namespace ReadJson
{
class Program
{
static void Main(string[] args)
{
string filePath = "<full path to json file>";
string json = File.ReadAllText(filePath);
var expandoConverter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, expandoConverter);
//do more with your dynamic object here...
}
}
}

Looking for Hello World program for Solr.NET in C#

I have Solr server running (on Linux box, not that it matter), it is loaded with 2M documents and search works fine in Java.
I need however to write C# (client) program to query it. I downloaded Solr.NET but I am confused what to begin with. Solutions included with it do not compile, and browsing through C# it does not look like the program is doing what I need to do.
Does anyone have a sort of Hello World program for Solr.NET in C#? Below I will publish Java version of what I and looking for, C# version anyone? Oh, and please, what minimum set of assemblies do I need to include into such simple client program? Thank you
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
public class SolrHeloWorld // Java
{
public static void main(String[] args)
{
// Connect to server
SolrServer solr = new HttpSolrServer ("http://192.168.1.211:8983/solr/collection1");
// Query for search term 'banana'
SolrQuery query = new SolrQuery();
query.setQuery("banana");
query.setStart(0);
query.setRows(50);
query.set("defType", "edismax");
try
{
QueryResponse response = solr.query(query);
// Print results
SolrDocumentList results = response.getResults();
for (int i = 0; i < results.size(); i++)
{
System.out.println(results.get(i));
}
}
catch (Exception e)
{
System.out.println("Error: " + e.getMessage());
}
}
}
As suggested I have take another closer look at documentation for Solr.NET. Still, I wasn’t able to figure out which assemblies are missing in solutions that came with download so they still do not compile! More importantly it does not appear that you can write bare bone program that simply prints JSON without NHibernate, defining class mapping and all that.
Never the less, it is not that hard to write simple Hello World client program in C# that queries Solr. And it does not require Solr.NET at all! Here is the one that uses HttpWebRequest and JSON serializer/deserializer to simply print JSON of all documents returned by query
using System;
using System.Net;
using System.IO;
using System.Web.Script.Serialization; // Require adding System.Web.Extentions.dll
class SolrHeloWorld // C#
{
static void Main()
{
Uri uri = new Uri("http://192.168.1.211:8983/solr/collection1/select?q=banana&start=0&rows=50&wt=json&indent=true&defType=edismax");
WebRequest request = HttpWebRequest.Create(uri);
request.Method = WebRequestMethods.Http.Get;
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string jsonResponse = reader.ReadToEnd();
response.Close();
JavaScriptSerializer serializer = new JavaScriptSerializer();
dynamic jsonObject = serializer.Deserialize<dynamic>(jsonResponse);
dynamic dd = jsonObject["response"]["docs"];
Object[] results = (Object[])dd;
foreach (Object res in results)
{
Console.WriteLine(serializer.Serialize(res));
}
}
}
There is a course in Pluralsight that gets you started with Solr and SolrNet. The last module is about SolrNet specifically:
http://www.pluralsight.com/courses/enterprise-search-using-apache-solr

Parsing the JSON with multilingual text using System.Web.Script.Serialization or System.Web.* library

I had asked this question before. The solution using Newtonsoft worked great until I deployed the website on web hosting server, where its giving me nightmares. Therefore, I am planning to use some System.Web libraries so that I don't have to deal with *.dlls and such and I can easily deploy my website.
Can someone help me parse the same json output using System.Web.Script.Serialization or any System library? Thanks a lot.
I hope your real json string is valid since the one you posted is corrupted but Json.Net tolerates it.
The only trick is deserializing to this funny type List<Dictionary<string,object>>
Here is an example with corrected json(removed trailing ,s)
string json = #"[ { ""ew"" : ""bharat"", ""hws"" : [ ""\u092D\u093E\u0930\u0924"",""\u092D\u0930\u0924"",""\u092D\u0930\u093E\u0924"",""\u092D\u093E\u0930\u093E\u0924"",""\u092C\u0939\u0930\u0924"" ] }, { ""ew"" : ""india"", ""hws"" : [ ""\u0907\u0902\u0921\u093F\u092F\u093E"",""\u0907\u0928\u094D\u0921\u093F\u092F\u093E"",""\u0907\u0923\u094D\u0921\u093F\u092F\u093E"",""\u0908\u0928\u094D\u0921\u093F\u092F\u093E"",""\u0907\u0928\u0921\u093F\u092F\u093E"" ] } ]";
var list = new JavaScriptSerializer().Deserialize<List<Dictionary<string,object>>>(json);
foreach (var dict in list)
{
var ew = (string)dict["ew"];
var firstValOfHws = ((ArrayList)dict["hws"])[0];
}
--EDIT--
OK, This should work
var serializer = new DataContractJsonSerializer(typeof(List<Result>));
var result = (List<Result>)serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));
public class Result
{
public string ew;
public List<string> hws;
}

Categories

Resources