-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathJsonString.cs
More file actions
72 lines (62 loc) · 2.09 KB
/
Copy pathJsonString.cs
File metadata and controls
72 lines (62 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright © 2019 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
namespace CefSharp.Web
{
/// <summary>
/// Represents a JsonString that is converted to a V8 Object
/// Used as a return type of bound methods
/// </summary>
public class JsonString
{
/// <summary>
/// JSON String
/// </summary>
public string Json { get; private set; }
/// <summary>
/// Default constructor
/// </summary>
/// <param name="json">JSON string</param>
public JsonString(string json)
{
if (json == null)
{
throw new ArgumentNullException("json");
}
Json = json;
}
/// <inheritdoc/>
public override string ToString()
{
return Json;
}
/// <summary>
/// Create a JsonString from the specfied object using the build in <see cref="DataContractJsonSerializer"/>
/// </summary>
/// <param name="obj">object to seriaize</param>
/// <param name="settings">optional settings</param>
/// <returns>If <paramref name="obj"/> is null then return nulls otherwise a JsonString.</returns>
public static JsonString FromObject(object obj, DataContractJsonSerializerSettings settings = null)
{
if (obj == null)
{
return null;
}
using (var ms = new MemoryStream())
{
var dataContractJsonSerializer = new DataContractJsonSerializer(obj.GetType(), settings);
dataContractJsonSerializer.WriteObject(ms, obj);
var jsonString = Encoding.UTF8.GetString(ms.ToArray());
if (string.IsNullOrEmpty(jsonString))
{
return null;
}
return new JsonString(jsonString);
}
}
}
}