本文整理汇总了C#中Newtonsoft.Json.JsonTextWriter类的典型用法代码示例。如果您正苦于以下问题:C# JsonTextWriter类的具体用法?C# JsonTextWriter怎么用?C# JsonTextWriter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JsonTextWriter类属于Newtonsoft.Json命名空间,在下文中一共展示了JsonTextWriter类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SerializeMessage
public static Message SerializeMessage(JObject json, Message previousMessage)
{
using (MemoryStream ms = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(ms))
{
using (JsonTextWriter jtw = new JsonTextWriter(sw))
{
json.WriteTo(jtw);
jtw.Flush();
sw.Flush();
Message result = Message.CreateMessage(MessageVersion.None, null, new RawBodyWriter(ms.ToArray()));
if (previousMessage != null)
{
result.Properties.CopyProperties(previousMessage.Properties);
result.Headers.CopyHeadersFrom(previousMessage.Headers);
previousMessage.Close();
}
result.Properties[JsonRpcConstants.JObjectMessageProperty] = json;
return result;
}
}
}
}
示例2: WriteTo
public static void WriteTo(this Item item, JsonTextWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(item.Format));
writer.WriteValue(Enum.GetName(typeof(SecsFormat), item.Format));
if (item.Format == SecsFormat.List)
{
writer.WritePropertyName(nameof(item.Items));
writer.WriteStartArray();
foreach (var subitem in item.Items)
subitem.WriteTo(writer);
writer.WriteEndArray();
}
else
{
writer.WritePropertyName(nameof(item.Values));
if (item.Format == SecsFormat.ASCII || item.Format == SecsFormat.JIS8)
{
writer.WriteValue(item.GetValue<string>());
}
else
{
writer.WriteStartArray();
foreach (var value in item.Values)
writer.WriteValue(value);
writer.WriteEndArray();
}
}
writer.WriteEndObject();
}
示例3: ExecuteResult
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
if (this.JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException("To allow GET requests, set JsonRequestBehavior to AllowGet.");
}
if (this.Data == null)
return;
var response = context.HttpContext.Response;
response.ContentType = string.IsNullOrEmpty(this.ContentType) ? "application/json" : this.ContentType;
if (this.ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
var serializer = JsonSerializer.Create(this.Settings);
using (var writer = new JsonTextWriter(response.Output))
{
serializer.Serialize(writer, Data);
writer.Flush();
}
}
示例4: ExportJson
private static string ExportJson(IEnumerable<SpriteFragment> fragments, string imageFile)
{
var map = new
{
images = fragments.Select(fragment =>
{
var item = new
{
Name = Path.GetFileName(fragment.FileName),
Width = fragment.Width,
Height = fragment.Height,
OffsetX = fragment.X,
OffsetY = fragment.Y,
};
return item;
})
};
string outputFile = GetFileName(imageFile, ExportFormat.Json);
ProjectHelpers.CheckOutFileFromSourceControl(outputFile);
using (StreamWriter sw = new StreamWriter(outputFile))
using (JsonWriter jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
var serializer = new JsonSerializer();
serializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
serializer.Serialize(jw, map);
}
return outputFile;
}
示例5: SaveToFile
public static void SaveToFile()
{
try
{
JsonSerializer serializer = new JsonSerializer();
var prices = dataAccess.GetAllPrices();
var sales = dataAccess.GetAllSales();
var priceChanges = dataAccess.GetPriceChanges();
string path = DataDir + "\\Prices.json";
var writer = new JsonTextWriter(File.CreateText(path));
serializer.Serialize(writer, prices);
writer.Close();
path = DataDir + "\\Sales.json";
writer = new JsonTextWriter(File.CreateText(path));
serializer.Serialize(writer, sales);
writer.Close();
path = DataDir + "\\priceChanges.json ";
writer = new JsonTextWriter(File.CreateText(path));
serializer.Serialize(writer, priceChanges);
writer.Close();
}
catch (Exception iException)
{
int x = 10;
throw;
}
}
示例6: parameterFieldMapJson
/// <summary>
/// Convert parameter list to json object
/// </summary>
public static string parameterFieldMapJson(parameters parms, string ProjectID, string QueryID)
{
StringWriter sw = new StringWriter();
JsonTextWriter json = new JsonTextWriter(sw);
json.WriteStartObject();
json.WritePropertyName("results");
json.WriteStartArray();
json.WriteStartObject();
// ProjectID and QueryID
json.WritePropertyName("ProjectID");
json.WriteValue(ProjectID);
json.WritePropertyName("QueryID");
json.WriteValue(QueryID);
json.WritePropertyName("parameters");
json.WriteRawValue(JsonConvert.SerializeObject(parms));
json.WriteEndObject();
json.WriteEndArray();
json.WriteEndObject();
json.Flush();
sw.Flush();
return sw.ToString();
}
示例7: Execute
public override void Execute(object parameter)
{
var saveFile = new SaveFileDialog
{
/*TODO, In Silverlight 5: DefaultFileName = string.Format("Dump of {0}, {1}", ApplicationModel.Database.Value.Name, DateTimeOffset.Now.ToString()), */
DefaultExt = ".raven.dump",
Filter = "Raven Dumps|*.raven.dump",
};
if (saveFile.ShowDialog() != true)
return;
stream = saveFile.OpenFile();
gZipStream = new GZipStream(stream, CompressionMode.Compress);
streamWriter = new StreamWriter(gZipStream);
jsonWriter = new JsonTextWriter(streamWriter)
{
Formatting = Formatting.Indented
};
output(String.Format("Exporting to {0}", saveFile.SafeFileName));
output("Begin reading indexes");
jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("Indexes");
jsonWriter.WriteStartArray();
ReadIndexes(0).Catch(exception => Infrastructure.Execute.OnTheUI(() => Finish(exception)));
}
示例8: SerializeMedicaments
public static void SerializeMedicaments(IPharmacyContext context)
{
var productsReports =
from medicament in context.Medicaments
join sale in context.Sales on medicament.MedicamentId equals sale.MedicamentId
select new
{
MedicamentId = medicament.MedicamentId,
MedicamentName = medicament.Name,
ManufacturerName = medicament.Manufacturer.Name,
Quantity = sale.Quantity,
Income = sale.Quantity * sale.UnitPrice
};
JsonSerializer serializer = new JsonSerializer();
foreach (var sale in productsReports)
{
var currentSaleFile = "../../../Reports/JsonReports/" + sale.MedicamentId + ".json";
using (var fileStream = new FileStream(currentSaleFile, FileMode.Create))
using (var streamWriter = new StreamWriter(fileStream))
using (var jsonWriter = new JsonTextWriter(streamWriter))
{
jsonWriter.Formatting = Formatting.Indented;
serializer.Serialize(jsonWriter, sale);
}
}
}
示例9: ExecuteResult
public override void ExecuteResult(ControllerContext context)
{
JsonSerializer json = new JsonSerializer();
json.NullValueHandling = NullValueHandling.Ignore;
json.ObjectCreationHandling = ObjectCreationHandling.Replace;
json.MissingMemberHandling = MissingMemberHandling.Ignore;
json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
String output = String.Empty;
StringWriter sw = new StringWriter();
JsonTextWriter writer = new JsonTextWriter(sw);
writer.Formatting = Formatting.Indented;
writer.QuoteChar = '"';
json.Serialize(writer, this.Data);
output = sw.ToString();
writer.Close();
sw.Close();
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.Write(output);
}
示例10: GetJsonString
static string GetJsonString(object obj)
{
using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream, Encoding.UTF8))
{
using (var jsonTextWriter = new JsonTextWriter(streamWriter)
{
Formatting = Formatting.None
})
{
var jsonSerializer = new JsonSerializer
{
Converters =
{
new JsonEnumConverter()
},
};
jsonSerializer.Serialize(jsonTextWriter, obj);
}
streamWriter.Flush();
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
示例11: Serialize
public static void Serialize(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath, Stream targetStream)
{
var json = JObject.FromObject(new
{
version = "2.0.0",
songSourcePath,
songs = songs.Select(song => new
{
album = song.Album,
artist = song.Artist,
duration = song.Duration.Ticks,
genre = song.Genre,
path = song.OriginalPath,
title = song.Title,
trackNumber = song.TrackNumber,
artworkKey = song.ArtworkKey
}),
playlists = playlists.Select(playlist => new
{
name = playlist.Name,
entries = playlist.Select(entry => SerializeSong(entry.Song))
})
}, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore });
using (var sw = new StreamWriter(targetStream, Encoding.UTF8, 64 * 1024, true))
using (var jw = new JsonTextWriter(sw))
{
jw.Formatting = Formatting.Indented;
json.WriteTo(jw);
}
}
示例12: ExecuteResult
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
HttpResponseBase response = context.HttpContext.Response;
response.ContentType = !string.IsNullOrEmpty(ContentType)
? ContentType
: "application/json";
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
示例13: Execute
public override bool Execute()
{
if (Items.Length == 0)
throw new ArgumentException("The provided items contained zero entries.");
if (!Directory.Exists(Path.GetDirectoryName(JsonFileName)))
Directory.CreateDirectory(Path.GetDirectoryName(JsonFileName));
JsonSerializer jsonSerializer = new JsonSerializer();
using (StreamWriter streamWriter = new StreamWriter(JsonFileName))
{
using (JsonTextWriter jsonWriter = new JsonTextWriter(streamWriter))
{
jsonWriter.Formatting = Formatting.Indented;
if (Items.Length > 1)
jsonWriter.WriteStartArray();
foreach (ITaskItem item in Items)
{
var customMd = item.CloneCustomMetadata();
jsonWriter.WriteStartObject();
foreach (var key in customMd.Keys)
{
var mdString = key.ToString();
var mdValue = customMd[key].ToString();
jsonWriter.WritePropertyName(mdString);
// if the value is surrounded in square brackets it's meant to be an array.
// split the value into its respective chunks and write it into a JSON array.
if (mdValue.Length > 0 && mdValue[0] == '[' && mdValue[mdValue.Length - 1] == ']')
{
mdValue = mdValue.Substring(1, mdValue.Length - 2);
jsonWriter.WriteStartArray();
var parts = mdValue.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
jsonWriter.WriteValue(part);
jsonWriter.WriteEndArray();
}
else
{
jsonWriter.WriteValue(mdValue);
}
}
jsonWriter.WriteEndObject();
}
if (Items.Length > 1)
jsonWriter.WriteEndArray();
Log.LogMessage(MessageImportance.High, "Writing {0}.", JsonFileName);
}
}
return true;
}
示例14: Dump
public void Dump()
{
try
{
var schema = this.CurrentSchema;
ContentRepository.ChangeProblems.Do(cp => schema.ApplyProblem(this.LastSchema, cp));
DirectoryInfo di = new DirectoryInfo(Paths.AppDataPath + "\\ContentSchema");
if (!di.Exists)
di.Create();
FileInfo fi = new FileInfo(Paths.AppDataPath + "\\ContentSchema\\LastSchema.json");
var sz = new JsonSerializer();
sz.Formatting = Formatting.Indented;
using (var stream = fi.OpenWrite())
using (var writer = new StreamWriter(stream))
using (var jsonTextWriter = new JsonTextWriter(writer))
{
sz.Serialize(writer, schema);
}
}
catch (Exception ex)
{
log.Error("Error creating content schema module dump: ", ex);
}
}
示例15: BasicRequest
//JsonWriter writer = new JsonTextWriter();
protected static string BasicRequest(int requestID, string method, string sessionID, params string[] parameters)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("jsonrpc");
writer.WriteValue("2.0");
writer.WritePropertyName("id");
writer.WriteValue(requestID);
writer.WritePropertyName("method");
writer.WriteValue(method);
writer.WritePropertyName("params");
writer.WriteStartArray();
writer.WriteValue(sessionID);
foreach (var p in parameters)
writer.WriteValue(p);
writer.WriteEndArray();
writer.WriteEndObject();
return sb.ToString();
//return sb.ToString().Replace("\n","");
}
}