Обновлено
Я полностью переработал этот вопрос и включил полный рабочий пример.
Теперь мой краткий вопрос: почему я не вижу отдельные символы строки «\ u001d», когда я использую RestSharp RestClient и выбираю json в качестве параметров RequestFormat для отправки простого объекта на сервер? Я отправляю вывод на тестовый сервер и вижу только 1d, когда проверяю вывод в двоичном редакторе. Я бы ожидал 5C 75 30 30 31 64
('\','u','0','0','1','d') И это то, что вы увидите, если просто используете NewtonSoft.Json для сериализации одного и того же простого объекта, содержащего строка «=». Насколько я понимаю, RestSharp сериализует ваш объект как .json (если вы выберете соответствующие параметры) и отправит на сервер для десериализации.
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Serializers;
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// To Test this,
/// 1. I first serialize a string to JSON and then print out the JSON string as a character array to show that
/// '\' 'u' '0' '0' '1' 'd' all show up in the serialized json string. I also put in original string \\001d (double \) for use later with RestSharp.
/// 2. I expect this json string to show up if I use RestSharp to send an object to a web service because RestSharp serializes everything to JSON
/// if it's so configured.
/// I make use of http://posttestserver.com/ to
/// act as "server", so I can just examine the data on that site. I copy the data on the server to a text file and open with binary editor.
/// Notice that there is just a '1d' present between 12 and 34.
/// You can perhaps duplicate what you get with just serialization by starting with (double \). But why should you need to do that?
/// Notice I try both RestClient's serializer and try to use NewtonSoft Serializer w/ RestClient.
/// 3. Finally I tried to send the serialized string with a client that had not been set up for JSON. Unfortunately, on server, it just shows up
/// as <String />. Not sure if it's me setting up client incorrectly or what's going on.
/// </summary>
class Program
{
static void Main(string[] args)
{
Tank tank1 = new Tank();
string string1 = "12\u001d34" + " " + "56\\u001d78" ; // you don't need double \\ with just serialization, but perhaps you need them with RestClient?
tank1.Description = string1;// new string(array1);
tank1.Id = 1;
// Show that we can serialize and each character of \u001d shows up as
JsonSerializerSettings settings = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
string conversion1 = JsonConvert.SerializeObject(tank1, Formatting.Indented, settings);
Console.WriteLine("JSON serialized string (showing hidden characters");
foreach(char dummyChar in conversion1.ToCharArray())
{
Console.Write(dummyChar + " ");
//Console.Write(conversion1.ToCharArray()[i] + " ");
} Console.WriteLine();
// Demonstrate that straight RestClient doesn't work.
RestClient client1 = new RestClient("http://posttestserver.com/"); // a website that let's you push data at it.
var request = new RestRequest(Method.POST); // method is Method.POST
request.AddHeader("Content-Type", "application/json");
request.AddHeader("X-ACME-API-VERSION", "1");
request.Resource = "post.php?dir=David"; // Put in unique name that you can easily find at http://posttestserver.com/data/2016/
request.RequestFormat = DataFormat.Json;
request.AddBody(tank1);
var response = client1.Execute(request); // after this line, go examine http://posttestserver.com/data/2016/ and find your post
// copy text to text file and open with binary editor. I claim you will see a 1d but not / (47) or u (117) or 0 (48) i.e. just 1d but not \u001d
// now try RequestClient w/ json serializer....
request.JsonSerializer = new JsonSerializerNewtonSoft();
response = client1.Execute(request);
// Finally, try just sending the json serialized stuff with a RestClient that has NOT been set to json stufff
RestClient client3 = new RestClient("http://posttestserver.com/"); // a website that let's you push data at it.
request.Resource = "post.php?dir=David"; // Put in unique name that you can find at http://posttestserver.com/data/2016/
var request3 = new RestRequest(Method.PUT); // method is Method.PUT // not sure what to put here
//request3.AddHeader("Content-Type", "application/json"); // not sure what to use here if anything
request3.AddHeader("X-ACME-API-VERSION", "1");
request3.Resource = "post.php?dir=David"; // Put in unique name that you can find at http://posttestserver.com/data/2016/
request3.RequestFormat = DataFormat.Xml; // not sure what to use here
request3.AddBody(conversion1);
var response3 = client3.Execute(request3); // hard to evaluate. Shows up at test server as <String />
}
}
interface ITank
{
int Id { get; set; }
string Description { get; set; }
}
public class Tank : ITank
{
public Tank() { }
public string Description { get; set; }
public int Id { get; set; }
}
public class Tanks
{
public Tanks() { }
public IEnumerable<Tank> Group { get; set; }
}
public class JsonSerializerNewtonSoft : ISerializer
{
private readonly Newtonsoft.Json.JsonSerializer _serializer;
/// <summary>
/// Default serializer
/// </summary>
public JsonSerializerNewtonSoft()
{
ContentType = "application/json";
_serializer = new Newtonsoft.Json.JsonSerializer
{
MissingMemberHandling = MissingMemberHandling.Ignore,
NullValueHandling = NullValueHandling.Include,
DefaultValueHandling = DefaultValueHandling.Include
};
}
/// <summary>
/// Default serializer with overload for allowing custom Json.NET settings
/// </summary>
public JsonSerializerNewtonSoft(Newtonsoft.Json.JsonSerializer serializer)
{
ContentType = "application/json";
_serializer = serializer;
}
/// <summary>
/// Serialize the object as JSON
/// </summary>
/// <param name="obj">Object to serialize</param>
/// <returns>JSON as String</returns>
public string Serialize(object obj)
{
using (var stringWriter = new StringWriter())
{
using (var jsonTextWriter = new JsonTextWriter(stringWriter))
{
jsonTextWriter.Formatting = Formatting.Indented;
jsonTextWriter.QuoteChar = '"';
_serializer.Serialize(jsonTextWriter, obj);
var result = stringWriter.ToString();
return result;
}
}
}
/// <summary>
/// Unused for JSON Serialization
/// </summary>
public string DateFormat { get; set; }
/// <summary>
/// Unused for JSON Serialization
/// </summary>
public string RootElement { get; set; }
/// <summary>
/// Unused for JSON Serialization
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// Content type for serialized content
/// </summary>
public string ContentType { get; set; }
}
for
в конце циклаMain
. Не уверен, что вы там задумали. - person Brian Rogers   schedule 10.11.2016<pre>
для форматирования кода — все, что имеет отступ в 4 или более пробела в редакторе, будет автоматически отформатировано как код. См. страницу справки Markdown. - person Brian Rogers   schedule 10.11.2016