forked from Zutatensuppe/DiabloInterfaceAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsonStreamReader.cs
More file actions
68 lines (58 loc) · 1.95 KB
/
Copy pathJsonStreamReader.cs
File metadata and controls
68 lines (58 loc) · 1.95 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
using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace DiabloInterfaceAPI
{
internal class JsonStreamReader
{
BinaryReader reader;
Encoding encoding;
public JsonStreamReader(Stream stream, Encoding encoding)
{
reader = new BinaryReader(stream);
this.encoding = encoding;
}
string ReadJsonString()
{
int length = reader.ReadInt32();
byte[] buffer = new byte[length];
int read = reader.Read(buffer, 0, length);
if (read != length) return null;
return encoding.GetString(buffer);
}
async Task<string> ReadJsonStringAsync()
{
// Get string length.
byte[] buffer = new byte[4];
int read = await reader.BaseStream.ReadAsync(buffer, 0, 4);
if (read != 4) return null;
int length = BitConverter.ToInt32(buffer, 0);
// Read string bytes.
buffer = new byte[length];
read = await reader.BaseStream.ReadAsync(buffer, 0, length);
if (read != length) return null;
// Convert to correct encoding.
return encoding.GetString(buffer);
}
public object ReadJson()
{
string jsonData = ReadJsonString();
if (jsonData == null) return null;
return JsonConvert.DeserializeObject(jsonData);
}
public T ReadJson<T>() where T : class
{
string jsonData = ReadJsonString();
if (jsonData == null) return null;
return JsonConvert.DeserializeObject<T>(jsonData);
}
public async Task<T> ReadJsonAsync<T>() where T : class
{
string jsonData = await ReadJsonStringAsync();
if (jsonData == null) return null;
return JsonConvert.DeserializeObject<T>(jsonData);
}
}
}