Как правильно проанализировать json в C# [закрыто]C#

Место общения программистов C#
Ответить
Anonymous
 Как правильно проанализировать json в C# [закрыто]

Сообщение Anonymous »

У меня есть следующий json в файле, который я назвал dtmdiom.json :
{"columns":"1"
,"gapx":"2"
,"gapy":"2"
,"iomask":"0xffff"
,"name":"5069-IB16F"
,"offcolor":"0xff000000"
,"oncolor":"0xff00ff00"
,"shapewidth":"16"
,"shapeheight":"16"
,"showtags":"true"}
< /code>
Моя логика в c#: < /p>
public void AddControl() {
//Look for the parent panel
Log.Info($"CWD: {System.IO.Directory.GetCurrentDirectory()}");
IUANode iuaNode = iuanGetSpecificOwnerType(Owner, Owner.GetType());
Log.Info($"Checking for {mstrFileSpec}");
if (File.Exists(mstrFileSpec)) {
//Read configuration from file
Log.Info($"Found: {mstrFileSpec}, reading...");
using FileStream fs = new FileStream(mstrFileSpec
, FileMode.Open
, FileAccess.Read);
using StreamReader rdr = new StreamReader(fs);
string strContent = rdr.ReadToEnd().Trim();
Log.Info(strContent);
byte[] arybytContent = System.Text.Encoding.ASCII.GetBytes(strContent);
if (arybytContent != null) {

JSObject json = JsonSerializer.Deserialize(arybytContent);
Log.Info(json.ToString());
}
}
}
< /code>
Это не удается со следующей сообщением об ошибке: < /p>
FTOptix.NetLogic;Warning;2;Error invoking method 'AddControl' in NetLogic Root/Objects/NewHMIProject/UI/MainWindow/scr1/pnlAll/hloColumns/Panel1/dtmDigital_IO_Module:
System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'System.Runtime.InteropServices.JavaScript.JSObject'. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
---> System.NotSupportedException: Deserialization of types without a parameterless constructor, a singular parameterized constructor, or a parameterized constructor annotated with 'JsonConstructorAttribute' is not supported. Type 'System.Runtime.InteropServices.JavaScript.JSObject'.
--- End of inner exception stack trace ---
at System.Text.Json.ThrowHelper.ThrowNotSupportedException(ReadStack& state, Utf8JsonReader& reader, NotSupportedException ex)
at System.Text.Json.Serialization.Converters.ObjectDefaultConverter`1.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value, Boolean& isPopulatedValue)
at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadFromSpan[TValue](ReadOnlySpan`1 utf8Json, JsonTypeInfo`1 jsonTypeInfo, Nullable`1 actualByteCount)
at System.Text.Json.JsonSerializer.Deserialize[TValue](ReadOnlySpan`1 utf8Json, JsonSerializerOptions options)
at dtmDigital_IO_Module.AddControl()
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr);
FTOptix.NetLogic.LogicBehavior.ExecuteMethod()

< /code>
Вышеуказанное все относится к строке, которая считывает: < /p>
JSObject json = JsonSerializer.Deserialize(arybytContent);
< /code>
Может ли кто-нибудь помочь? class clsDIOM {
[JsonPropertyName("columns")]
public String Colunns { get; set; }

[JsonPropertyName("gapx")]
public String GapX { get; set; }

[JsonPropertyName("gapy")]
public String GapY { get; set; }

[JsonPropertyName("iomask")]
public String IOmask { get; set; }

[JsonPropertyName("name")]
public String Name { get; set; }

[JsonPropertyName("offcolor")]
public String OffColor { get; set; }

[JsonPropertyName("oncolor")]
public String OnColor { get; set; }

[JsonPropertyName("shapewidth")]
public String ShapeWidth { get; set; }

[JsonPropertyName("shapeheight")]
public String ShapeHeight { get; set; }

[JsonPropertyName("showtags")]
public String ShowTags { get; set; }
}
< /code>
Измененная логика на: < /p>
public async Task AddControl() {
// Log.Info($"52 Owner: {Owner.BrowseName}");
// NodeId nid = Owner.NodeId;
// var objPanel = InformationModel.Get(nid);
// if (objPanel != null) {
// Log.Info($"56 objPanel:[{objPanel}]");
// Log.Info($"57 objPanel.Width:[{objPanel.Width}]");
// Log.Info($"58 objPanel.Height:[{objPanel.Height}]");
// }
//Look for the parent panel
Log.Info($"CWD: {System.IO.Directory.GetCurrentDirectory()}");
IUANode iuaNode = iuanGetSpecificOwnerType(Owner, Owner.GetType());
Log.Info($"Checking for {mstrFileSpec}");
if (File.Exists(mstrFileSpec)) {
//Read configuration from file
Log.Info($"Found: {mstrFileSpec}, reading...");
var fileContents = File.ReadAllText(mstrFileSpec);
var json = JsonSerializer.Deserialize(fileContents);
Log.Info(json.ToString());
}
}

Когда я выполняю AddControl I Que Get:
2025-07-09 15:06:41.925;FTOptix.NetLogic;223;Warning;2;Error invoking method 'AddControl' in NetLogic Root/Objects/NewHMIProject/UI/MainWindow/scr1/pnlAll/hloColumns/Panel1/dtmDigital_IO_Module:
System.Reflection.TargetParameterCountException: Parameter count mismatch.
at System.Reflection.MethodBaseInvoker.ThrowTargetParameterCountException()
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at FTOptix.NetLogic.NetCodeExecutor.c__DisplayClass2_0.b__0() in C:\jenkins\workspace\FTOptix_BuildDeploy\src\NetLogic\NetLogic\src\NetCodeExecutor.cs:line 60
at FTOptix.NetLogic.NetCodeExecutor.Invoke(Action action) in C:\jenkins\workspace\FTOptix_BuildDeploy\src\NetLogic\NetLogic\src\NetCodeExecutor.cs:line 110
at FTOptix.NetLogic.NetCodeExecutor.InvokeUserMethod(Action action, String methodName) in C:\jenkins\workspace\FTOptix_BuildDeploy\src\NetLogic\NetLogic\src\NetCodeExecutor.cs:line 94
at FTOptix.NetLogic.NetCodeExecutor.ExecuteMethod(String methodName, Object[] inputArgs) in C:\jenkins\workspace\FTOptix_BuildDeploy\src\NetLogic\NetLogic\src\NetCodeExecutor.cs:line 60
at FTOptix.NetLogic.LogicBehavior.ExecuteMethod(IUANode targetNode, String methodName, Object[] inputArgs, Object[]& outputArgs) in C:\jenkins\workspace\FTOptix_BuildDeploy\src\NetLogic\NetLogic\src\LogicBehavior.cs:line 98;
FTOptix.NetLogic.LogicBehavior.ExecuteMethod()


Подробнее здесь: https://stackoverflow.com/questions/796 ... in-c-sharp
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»