i am new to c# and have a little problem. I have a JSON-file that includes some mailadresses. For each mailadress there are 4 fields (name, email[], imprint, info2) in this JSON-file. I want to convert this into an array or arraylist in my project and I am currently using Newtonsoft.Json to achieve this.
I made a class adress :
public class adress
{
public string name = "";
public string[] email = {""};
public string imprint = "";
public string info2 = "";
}
this is the json:
{"name":"test1","email":["[email protected]"],"imprint":"testimprint1 testimprint1","info2":"testinfo1"} {"name":"test2","email":["[email protected]"],"imprint":"testimprint2 testimprint2","info2":"testinfo2"} {"name":"test3","email":["[email protected]"],"imprint":"testimprint3 testimprint3","info2":"testinfo3"}
and try converting it like this:
List<adress> adresses = new List<adress>();
string json_adress = File.ReadAllText("C:\\Mail\\adresses.json");
adresses = JsonConvert.DeserializeObject<List<adress>>(json_adress);
I get the following error:
"Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[Mailer.adress]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly."`
Maybe someone can help me to understand this json-thing better?
2 Answers 2
You are almost there but a small mistake. What you supplied is as the following. Please take notice that there are no commas at the seperation.
{JSONSTUFF}
{JSONSTUFF}
{JSONSTUFF}
But the following says that you want it to be converted to List<address> but it is not a list :(
JsonConvert.DeserializeObject<List<adress>>(json_adress);
So in fact what you need to supply is a list of address,
[
{JSONSTUFF},
{JSONSTUFF},
{JSONSTUFF},
]
Please do not forget the commas :)
[{"name":"test1","email":["[email protected]"],"imprint":"testimprint1 testimprint1","info2":"testinfo1"}, {"name":"test2","email":["[email protected]"],"imprint":"testimprint2 testimprint2","info2":"testinfo2"}, {"name":"test3","email":["[email protected]"],"imprint":"testimprint3 testimprint3","info2":"testinfo3"}]
2 Comments
Assuming there are linebreaks after each object in the file:
var lines = File.ReadAllLines(@"your path");
List<adress> adresses = new List<adress>();
foreach (var line in lines)
{
adresses.Add(JsonConvert.DeserializeObject<adress>(line));
}
[and]-- and commas between objects? Without the outer brackets your file isn't a single valid JSON value, it's a concatenated series of JSON values. See json.org for the correct format. If your file really consists of concatenated JSON objects, you can use the solution from Load multiple concatenated JSON objects from stream. But please confirm this is what you have since it isn't proper JSON.