I have this code:
["ok", "Google", "google"]
That I get from decenturl.com/api-title?u=google.com. This API gets the title of a site, but it is "encoded" in the format above. What is the format of this? I tried to search for it, but without the name I can't do anything. It looks like JSON, but it isn't, I guess.
Anyway, how do I parse this in C#? Will be better if this work in framework 2.0, but if can't, I accept above frameworks. There is a built-in method for that? Or I need to do it manually?
Thanks.
It is JSON, just for an array. Assuming the URL always gives you back JSON, you could parse it like this (using Json.NET, which still supports .NET 2.0):
using System;
using Newtonsoft.Json.Linq;
class Test
{
static void Main()
{
string json = "[\"ok\", \"Google\", \"google\"]";
var array = JArray.Parse(json);
Console.WriteLine(array[0]); // For example
}
}
Related
I want to do this, but I want to also be able to pass in arrays into the query string. I've tried things like:
http://www.sitename.com/route?arr[]=this&arr[]=that
http://www.sitename.com/route?arr[]=this&that
http://www.sitename.com/route?arr[0]=this&arr[1]=that
http://www.sitename.com/route?arr0=this&arr1=that
http://www.sitename.com/route?arr=this&arr=that
And my route in the C# code looks like this:
[Route("route")]
[HttpGet]
public void DoSomething(string[] values)
{
// ...
}
But in all of these cases, values is always null when it gets to the C# code. What do I need my query string to be to pass an array of strings?
Use a parameter name in the query string. If you have an action:
public void DoSomething(string[] values)
Then use values in the query string to pass an array to a server:
?values=this&values=that
Delimited string is not the standard. Think also about the client if you support swagger or other generators.
For those who wonder about .net core 2.1 bug which receives an empty list, the work around is here: https://github.com/aspnet/Mvc/issues/7712#issuecomment-397003420
It needs a name parameter on FromQuery
[FromQuery(Name = "employeeNumbers")] List<string> employeeNumbers
I have found a solution. For example, if you have a query like this:
http://www.sitename.com/route?arr[]=this&arr[]=that
You must define in parameter as [FromQuery(Name = "arr[]")]. The name of parameter must include square brackets. As result we can see:
public void DoSomething([FromQuery(Name = "arr[]")] string[] arr)
I had to do something similar to this, but instead of strings, i used a list of long to pass some id for a search. Using a multiple select option, the chosen values are sent to the method (via get) like this:
[HttpGet("[action]")]
public IActionResult Search(List<long> idsSelected)
{
///do stuff here
}
I also use Route("[controller]") before the class declaration. Works just fine, but the list of items is broken into multiple parameters in the url, as shown below.
http://localhost:5000/Search/idsSelected=1&idsSelected=2
I found two problems in your question:
Your query has parameters named arr while you Contrller's Action has values.
I don't know why, but you gotta name your parameter (as answered here) so the Asp .NET ModelBinder can work as expected. Like this:
public void DoSomething([FromQuery(Name = "values")] string[] values)
After doing that, everything should work as expected.
Given:
public ValuesController
{
public IACtionResult Get([FromUri]string[] arr)
{
Return Ok(arr.Length);
}
}
The following request will work:
GET /api/values/?arr[0]=a&arr[1]=b&arr[2]=c
In the end, I just passed in a single delimited string, then used string.Split to separate on the server side. Not the prettiest solution, but it works. Until someone comes up with a better answer, this is all I got. I should reiterate that I'm using .NET Core, and these query strings are framework specific.
Update: An (arguable) benefit of this approach is that you pass the values together (e.g. arr=value1,value2) instead of repeating the key (arr=value1&arr=value2).
I had the same problem with .NET Core 3, while trying to pass in a string Array. I solved it by passing in the query parameter as a temporary json string. I then deserialized the string to the resulting array using Newtonsoft's Json package
using Newtonsoft.Json;
public IActionResult Get([FromQuery(Name = "array")] string arrayJson)
{
List<string> array = JsonConvert.DeserializeObject<List<string>>(arrayJson);
}
I've been browsing various websites and the JSON.net docs but I can't find an elegant way to do this.
The Problem
I have to parse a list of GitHub commits since a certain date.
The example json file I've been using for testing: example json file
The json is just a large (or empty) array. The problem is I don't need all of the data, I just need the sha of each commit.
However, if you look at each type in the array, there are multiple shas.
There is the base sha:
"sha": "fde139ae1d8fcf82bb145bbc99ed41763202e28f",
the tree sha:
"tree": {
"sha": "5d33d345f2df166bc4c56cc9307a61a5ee57d346",
"url": "https://api.github.com/repos/QuiZr/ProjectPorcupineLocalization/git/trees/5d33d345f2df166bc4c56cc9307a61a5ee57d346"
},
and the parent sha(s):
"parents": [
{
"sha": "8b9b43e813645c3a66911247b3dca916af937738",
"url": "https://api.github.com/repos/QuiZr/ProjectPorcupineLocalization/commits/8b9b43e813645c3a66911247b3dca916af937738",
"html_url": "https://github.com/QuiZr/ProjectPorcupineLocalization/commit/8b9b43e813645c3a66911247b3dca916af937738"
}
]
I only want the first sha. not the other shas.
Requirements
Needs to use JSON.net (not Ockokit)
Should be elegant
Needs to support the Unity game engine (i.e. C# version less than or equal to 2.0)
I really don't want to create a new object type just for this.
You can just use LINQ to JSON very easily in this case - parse the text as a JArray, then ask for the sha property of each object:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
class Test
{
static void Main()
{
string json = File.ReadAllText("test.json");
JArray array = JArray.Parse(json);
List<string> hashes = array.Select(o => (string) o["sha"]).ToList();
foreach (var hash in hashes)
{
Console.WriteLine(hash);
}
}
}
Note that this uses lambda expressions which are from C# 3, but that should be fine in Unity - it only supports the CLR v2, but the .NET 3.5 framework, I believe.
In future though, I wouldn't let concerns such as "It's only a small part of the codebase" put you off creating a type - if LINQ to JSON didn't exist, creating a model type for the commit and deserializing to that would be a perfectly good solution.
If you really do not want new type, you can deserialize it using anonymous types. http://www.newtonsoft.com/json/help/html/DeserializeAnonymousType.htm
Providing some contextual information: I want to integrate some technology with MongoDB using the official C# driver, but due some limitations I need to integrate it using only JSON strings. So, I'm building a simple wrapper to the native functions to call they by passing and receiving JSON as simple strings.
Example of the find method:
public string find(string json)
{
BsonDocument query = BsonDocument.Parse(json);
var list = Collection.Find(query).ToListAsync().Result;
return list.ToJson();
}
P.S.: I know the performance implications of using an async method as a synchronous one, but I have no choice.
This works pretty well, the problem is with the update/replace method:
public string updateMany(string jsonFilter, string jsonUpdate)
{
BsonDocument filter = BsonDocument.Parse(jsonFilter);
BsonDocument update = BsonDocument.Parse(jsonUpdate);
UpdateResult r = Collection.UpdateManyAsync(filter, update).Result;
return r.ToJson();
}
This returns the string: { "_t" : "Acknowledged" }, which only tells me the class of the UpdateManyAsync() result. That class expose some properties like MatchedCount and ModifiedCount that I would like to put on JSON too, but the default serializer is ignoring them by some reason (those properties are read-only, so should be ignored on deserializing, but not on serializing).
I tried to use r.ToJson<UpdateResult>(); and r.ToBsonDocument<UpdateResult>();, but got the same result.
I saw that toJson() has some overloads receiving a JsonWriterSettings, an IBsonSerializer and a BsonSerializationArgs, so maybe one of them holds some configuration about the subject, but I have no luck searching for it.
I think that I could import Json.NET DLL to see if it serializes all the properties, but I would like to solve it without another dependency.
Hi I'm quite new to C# and I'm trying to make a text editor that saves and loads Plaintext formats. I've used NewtonSoft.Json NuGet package, but I'm getting an error. I've stated a string called textToLoad, which is set to a JsonConvert.DeserializeObject. Only thing is, it says it can't convert an object to a string! I tried toString(); but it still had the same error.
It is kind of hard without the code. The process of serializing and deserializing is pretty straight forward using Json.Net. So this is an example from their documentation:
YourType yourObject= new YourType();
yourObject.Property="something";
string output = JsonConvert.SerializeObject(yourObject);
//For some reason you want this to be string, but is the type you serialized in the first place
YourType textToLoad= JsonConvert.DeserializeObject<YourType>(output);
This outlines the basic works of serializing and deserializing. But we don't really know the details of your implementation.
Hope it helps.
You can't deserialize into a string like that. At simplest form you started with JSON in the form of:
{ value: "someString" }
If you want something out of it, you must deserialize and then get the value from it.
dynamic foo = JsonConvert.DeserializeObject<dynamic>(theJson);
var textToLoad = foo.value.ToString();
You must deserialize to something in order to inspect and get properties from it.
[Edit] - Perhaps I'm not understanding. But if you share code, I'll update my answer.
I've got c# objects that I need references to in javascript for default population. Currently I'm maintaining 2 different objects which is not that maintainable.
For example ( simplified for demo purposes ):
C#
public class Text
{
public string Name {get;set;}
}
JSON
{
'text': {
name: undefined
}
}
I know there is a number of ways to accomplish this but wondering if anyone has a recommended solution. Thanks!
I personally recommend json.NET. Getting the json of any object is as simple as;
using Newtonsoft.Json;
string json = JsonConvert.SerializeObject(new Text { Name = "test" });
There are a lot of other options but I've been using it since before there was json serilization support in .NET and I strongly prefer it over what is there now. In fact I think it's better in every way, if you want a big robust data layer I like it more and it's vastly superior for one off serilizations.
If you are using .NET 4.0 or above, you can use DataContractJsonSerializer class.
I recommend you to look at this benchmark http://theburningmonk.com/2013/09/binary-and-json-serializer-benchmarks-updated/