I guess this is easy, but I am new and cannot find a fast answer to this:
I want to obtain a list of file names (List<string>) in a .Net 2.0 desktop app, using WebClient requesting to a WebAPI REST service.
So, I have this code in the desktop app:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.Accept] = "application/json";
var resultString = client.DownloadString("http://localhost:3788/api/file?src=X&dest=Y");
}
and a WebAPI action like this in the service:
public IEnumerable<string> GetFiles([FromUri]string src, [FromUri]string dest)
{
// some code here
}
How would I convert the resultString, which is a JSON String, to a List<String> ?
Do I have to use JsonDataContractSerializer?
Look at this SO question and answer. The code there outlines what you would do. The key is to reference the Newtonsoft.Json namespace (add it from a NuGet package) and use the DeserializeObject generic method. The answer shows other things you can do with results.
Related
I'm working on a personal project. Its a C# app that communicates with some web services using an API.
i finally got the first raw data with this few lines:
var client = new RestClient("https://api.abcd.com/token");
var request = new RestRequest(Method.POST);
request.AddParameter("username", usr);
request.AddParameter("password", pass);
request.AddParameter("grant_type", "password");
and in postman the response (JSON) looks like :
{"access_token":"aaaaaaa","token_type":"bearer","expires_in":899,"refresh_token":"bbbbbbb",".issued":"Fri,
01 May 2020 16:11:36 GMT",".expires":"Fri, 01 May 2020 16:26:36
GMT",".refreshexpires":"Fri, 01 May 2020 17:11:36 GMT"}
my next step is to find the way to separate those key/value pair into different variables in C# so i can work with them.
thank you so much for the help.
But I guess for small purpose no need to create a class rather use weakly typed data structure like this:
dynamic responseObject = JsonConvert.DeserializeObject(responseString);
//then use every property like this
responseObject.accessToken ...
responseObject.token_type.....
But you need to use Newtonsoft.Json for this too.
You want to use a JSON deserialiser to do this.
So you would create a class:
public class Response {
public string accessToken {get; set;)
public string token_type {get; set;)
.....
}
And then use something like Newtonsoft.Json (available from NuGet) to deserialise:
using Newtonsoft.Json;
.....
var response = JsonConvert.Deserialise<Response>([RAW TEXT FROM REST CLIENT]);
You can look into using Json.Net which will allow you to deserialize the JSON into an object like so. Note you'll need to download the package and then add using Newtonsoft.Json;
{
"varone":"valueone"
}
public class MyJsonClass
{
//JsonProperty isn't strictly required but I personally think it helps when trying to deserialize for sanity sake
[JsonProperty("varone")]
public string VarOneValue { get; set; } //The value will be "valueone" on deserialization
}
var myobj = JsonConvert.DeserializeObject<MyJsonObject>(JSONDATA);
Console.Write(myobj.VarOneValue); //Will be "valueone"
Nuget CLI: Install-Package Newtonsoft.Json
Page: https://www.newtonsoft.com/json
I have a legacy PHP application which is using PHP's serialize() method to serialize the class and store it to a file and there are other applications using this string using unserialize() method to create object of the serialized class and use the data associated. I need to achieve similar serialization technique in .NET so that the output is same as PHP. I am thinking to use Reflection for this but still need to identify how I will make use of that. I have also tried the .NET serialization but the output is totally different.
Is there any other way I can do this?
consider example below -
sample php class
class SerializeTest
{
var $test = 0;
var $test1 = "testing";
var $test2 = 1;
var $test3 = "testing1";
public function __construct()
{
echo serialize($this);
}
}
serialized string
O:13:"SerializeTest":4:{s:4:"test";i:0;s:5:"test1";s:7:"testing";s:5:"test2";i:1;s:5:"test3";s:8:"testing1";}
sample .NET Class
class SerializeDemo
{
internal int test = 0;
internal string test1 = "testing";
internal int test2 = 1;
internal string test3 = "testing3";
}
required serialized string
O:13:"SerializeTest":4:{s:4:"test";i:0;s:5:"test1";s:7:"testing";s:5:"test2";i:1;s:5:"test3";s:8:"testing1";}
Try the Sharp Serialization Library
Sharp Serialization Library serializes and deserializes primitives,
ArrayLists and Hashtables, compatible with PHP serialize(). Use it for
SOAP/Web Services communications where Hashtables cannot be passed
otherwise, or saving to a file readable by php.
With Xamarin Android, it possible to create localized strings for multi-language apps, as is shown in their Android documentation:
http://docs.xamarin.com/guides/android/application_fundamentals/resources_in_android/part_5_-_application_localization_and_string_resources
However, I have various try/catch blocks in my Model which send error messages back as strings. Ideally I'd like to keep the Model and Controller parts of my solution entirely cross platform but I can't see any way to effectively localize the messages without passing a very platform specific Android Context to the Model.
Does anyone have ideas about how this can be achieved?
I'm using .net resource files instead of the Android ones. They give me access to the strings from code, wherever it is.
The only thing I can't do automatically is reference those strings from layouts. To deal with that I've written a quick utility which parses the resx file and creates an Android resource file with the same values. It gets run before the Android project builds so all the strings are in place when it does.
Disclaimer: I haven't actually tested this with multiple languages yet.
This is the code for the utility:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace StringThing
{
class Program
{
static void Main(string[] args)
{
string sourceFile = args[0];
string targetFile = args[1];
Dictionary<string, string> strings = LoadDotNetStrings(sourceFile);
WriteToTarget(targetFile, strings);
}
static Dictionary<string, string> LoadDotNetStrings(string file)
{
var result = new Dictionary<string, string>();
XmlDocument doc = new XmlDocument();
doc.Load(file);
XmlNodeList nodes = doc.SelectNodes("//data");
foreach (XmlNode node in nodes)
{
string name = node.Attributes["name"].Value;
string value = node.ChildNodes[1].InnerText;
result.Add(name, value);
}
return result;
}
static void WriteToTarget(string targetFile, Dictionary<string, string> strings)
{
StringBuilder bob = new StringBuilder();
bob.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
bob.AppendLine("<resources>");
foreach (string key in strings.Keys)
{
bob.Append(" ");
bob.AppendLine(string.Format("<string name=\"{0}\">{1}</string>", key, strings[key]));
}
bob.AppendLine("</resources>");
System.IO.File.WriteAllText(targetFile, bob.ToString());
}
}
}
For Xamarin, you can also look at Vernacular https://github.com/rdio/vernacular
You can write code with minimal effort without worrying about the translation. Feed the generated IL to Vernacular to get translatable strings in iOS, Andorid, Windows Phone formats.
I've created a slightly ugly solution at Xamarin iOS localization using .NET which you might find helpful.
before writing my own :-)
I was wondering if anyone knows a tool to parse a URL and extract all the params into a easier viewable format, a grid maybe? (these urls are extremely long :- )
And also if it allows you to construct the querystring for standard text and automates the URL ENCODING etc.
Must be one available, i have searched high and low and can't find anything.
Thanks in advance
The ParseQueryString method is pretty handy for those tasks.
I was wondering if anyone knows a tool to parse a URL and extract all
the params into a easier viewable format, a grid maybe? (these urls
are extremely long :- )
using System;
using System.Web;
class Program
{
static void Main()
{
var uri = new Uri("http://foo.com/?param1=value1¶m2=value2");
var values = HttpUtility.ParseQueryString(uri.Query);
foreach (string key in values.Keys)
{
Console.WriteLine("key: {0}, value: {1}", key, values[key]);
}
}
}
And also if it allows you to construct the querystring for standard
text and automates the URL ENCODING etc.
using System;
using System.Web;
class Program
{
static void Main()
{
var values = HttpUtility.ParseQueryString(string.Empty);
values["param1"] = "value1";
values["param2"] = "value2";
var builder = new UriBuilder("http://foo.com");
builder.Query = values.ToString();
var url = builder.ToString();
Console.WriteLine(url);
}
}
Any idea on how to do it? If not possible, what's a good JSON library for C#?
System.Json is now available in non-Silverlight projects via NuGet (.Net's package management system) and is hopefully going to be released as part of the core framework in vnext. The NuGet package is named JsonValue.
Imagine that we have the following JSON in the string variable json:
[{"a":"foo","b":"bar"},{"a":"another foo","b":"another bar"}]
We can get write the value "another bar" to the console using the following code:
using System.Json;
dynamic jsonObj = JsonValue.Parse(json);
var node = jsonObj[1].b;
System.Console.WriteLine(node.Value);
Here's an extenstion method to serialize any object instance to JSON:
public static class GenericExtensions
{
public static string ToJsonString<T>(this T input)
{
string json;
DataContractJsonSerializer ser = new DataContractJsonSerializer(input.GetType());
using (MemoryStream ms = new MemoryStream())
{
ser.WriteObject(ms, input);
json = Encoding.Default.GetString(ms.ToArray());
}
return json;
}
}
You'll need to add a reference to System.ServiceModel.Web to use the DataContractSerializer.
Scott Guthrie blogged about this
http://weblogs.asp.net/scottgu/archive/2007/10/01/tip-trick-building-a-tojson-extension-method-using-net-3-5.aspx
If you're just looking for JSON encoding/decoding, there is an official System.Web extension library from Microsoft that does it, odds are you probably already have this assembly (System.Web.Extensions):
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
Example:
using System;
using System.Web.Script.Serialization;
class App
{
static void Main(string[] args = null)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
String sJson = "{\"Name\": \"Your name\"}";
DesJson json = jss.Deserialize<DesJson>(sJson);
Console.WriteLine(json.Name);
}
}
class DesJson {
public string Name {get; set;}
}
Another option is to use Mono's implementation of System.Json,
I was able to backport it to C# 2.0 with a few minor changes.
You can simply download my C# 2.0 project from here.