C#如何读取txt文件中的多个json数据

时间:2019-04-08 07:52:11

标签: c# json json.net

不好意思,我是C#的新秀。
我有一个这样的txt文件

{"ID":1,"ScrewDiameter":28.0,"InjectionStroke":139.7,"InjectionVolume":86.0,"InjectionPressure":1857.0,"InjectionRate":62.0,"ClampForce":55.0,"MinMoldHeight":180.0,"MaxStroke":380.0,"InjectionSpeed":100.0,"CreateDate":null}
{"ID":2,"ScrewDiameter":36.0,"InjectionStroke":140.0,"InjectionVolume":143.0,"InjectionPressure":1842.0,"InjectionRate":90.0,"ClampForce":85.0,"MinMoldHeight":200.0,"MaxStroke":450.0,"InjectionSpeed":100.0,"CreateDate":null}

我想显示两个数据

但它显示

Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0.


於 Newtonsoft.Json.JsonTextReader.ParseValue()
於 Newtonsoft.Json.JsonTextReader.ReadInternal()
於 Newtonsoft.Json.JsonTextReader.Read()
於 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract contract, Boolean hasConverter)
於 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
於 Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
於 Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)
於 Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)
於 Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
於 WindowsFormsAppgetData.Form1.ReadFromJsonFile[machine2](String filePath) 
於 C:\Users\Shih-Hao.Su\source\repos\WindowsFormsAppgetData\WindowsFormsAppgetData\Form1.cs: 行 50

'[[13104] WindowsFormsAppgetData.exe'程序以返回码-1(0xffffffff)结束。

我使用此示例

json

How to save/restore serializable object to/from file?

并更改    append = true

我期望的结果是

"ID":1,"ScrewDiameter":28.0,"InjectionStroke":139.7,"InjectionVolume":86.0,"InjectionPressure":1857.0,"InjectionRate":62.0,"ClampForce":55.0,"MinMoldHeight":180.0,"MaxStroke":380.0,"InjectionSpeed":100.0,"CreateDate":null
"ID":2,"ScrewDiameter":36.0,"InjectionStroke":140.0,"InjectionVolume":143.0,"InjectionPressure":1842.0,"InjectionRate":90.0,"ClampForce":85.0,"MinMoldHeight":200.0,"MaxStroke":450.0,"InjectionSpeed":100.0,"CreateDate":null 

1 个答案:

答案 0 :(得分:0)

1)创建一个文件,我将其命名为“ json.json”

2)将此数组放入其中:

[{"ID":1,"ScrewDiameter":28.0,"InjectionStroke":139.7,"InjectionVolume":86.0,"InjectionPressure":1857.0,"InjectionRate":62.0,"ClampForce":55.0,"MinMoldHeight":180.0,"MaxStroke":380.0,"InjectionSpeed":100.0,"CreateDate":null},{"ID":2,"ScrewDiameter":36.0,"InjectionStroke":140.0,"InjectionVolume":143.0,"InjectionPressure":1842.0,"InjectionRate":90.0,"ClampForce":85.0,"MinMoldHeight":200.0,"MaxStroke":450.0,"InjectionSpeed":100.0,"CreateDate":null}]

3)使用此代码:

List<dynamic> objs = JsonConvert.DeserializeObject<List<dynamic>>(File.ReadAllText("json.json"));