我正在接收带有嵌套json对象和json数组的不同的 JSON到C#app,并使用Newtonsoft.JSON
解析它们。我将此数据发送到MATLAB应用程序,并希望尽可能简单地将其发送给MATLAB,以便正确地将.NET
类型解析为MATLAB。
为此,我将JObject
转换为Dictionary<string, dynamic>
。我使用dynamic
,以便MATLAB始终获得int
,double
,String
而不是object
。
我还将JArray
转换为object[]
(using similar ToObject()
function as in that thread)。
我缺少的是将JArray
完全转换为double[]
,int[,]
的方法。等等,如果它们实际上属于那种类型。这将使MATLAB能够正确地将它们解析为MATLAB的double
,int32
等。
有没有办法实现这个目标?它也可以应用于多维数组吗?
澄清:如果我得到字符串数组,我不介意留下它object[]
。我主要关心数字多维数组。
修改 由于MATLAB更喜欢多维的锯齿状数组,因此我也是如此:)
现有代码:
我目前将以下Struct
类似的类型暴露给MATLAB,因为不可能将MATLAB结构编组为C#:
[JsonConverter(typeof(StructConverter))]
public class Struct
{
[JsonExtensionData]
Dictionary<string, dynamic> dict;
public Struct() => dict = new Dictionary<string, dynamic>();
public Struct(Dictionary<string, dynamic> d) => dict = d;
public string[] GetKeys() => dict.Keys.ToArray();
public void Set(string key, dynamic value) => dict[key] = value;
public void SetVector(string key, int[] value) => dict[key] = value;
public void SetVector(string key, double[] value) => dict[key] = value;
public dynamic Get(string key) => dict[key];
}
StructConverter
是我当前的转换器:
public class StructConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return ReadValue(reader);
}
private dynamic ReadValue(JsonReader reader)
{
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadObject(reader);
case JsonToken.StartArray:
return ReadArray(reader);
default:
return reader.Value;
}
}
private dynamic ReadObject(JsonReader reader)
{
MatNet.Struct s = new MatNet.Struct();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propName = reader.Value.ToString();
if (!reader.Read()) throw new Exception("Unexpected end when reading ExpandoObject.");
s.Set(propName, ReadValue(reader));
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return s;
}
}
throw new Exception("Unexpected end when reading ExpandoObject.");
}
private dynamic ReadArray(JsonReader reader)
{
List<dynamic> list = new List<dynamic>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
default:
list.Add(ReadValue(reader));
break;
case JsonToken.EndArray:
return list.ToArray();
}
}
throw new Exception("Unexpected end when reading ExpandoObject.");
}
}
我能够序列化和反序列化以下内容,但数组是object[]
而不是int[]
,string[]
和double[]
:
var d = new MatNet.Struct();
d.Set("a", new int[] { 1, 2, 4, 8, 16 });
d.Set("b", new string[] { "qwer", "tyui", "asdf", "ghjk" });
d.Set("c", new double[,] { {1, 3}, {2, 4}, {5, 7}, {6, 8} });
d.Set("d", new MatNet.Struct());
var json = JsonConvert.SerializeObject(d);
dynamic x = JsonConvert.DeserializeObject<MatNet.Struct>(json);