-1

I'm a beginner in C# development and I need your help.. I am checking all the subject in Stackoverflow but I can't find and fix my problem. I received a JSON response from an API and I would like to transform the data in object.

------------ Here my JSON response :

 {"code":200,"status":"success","message":"Request completed","data":      \[\[{"Matricule_Collaborateur":"455","Nom_Prenom_Collaborateur":"lastname_455 firstname_455","Jour_Presence":"01-12-2022","Adresse_Postale_Collaborateur":"","Code_Postal_Collaborateur":"","Ville_Collaborateur":"","Date_Naissance_Collaborateur":"01-01-1980","Titre_Collaborateur":null,"Email_Pro_Collaborateur":"email_455","Identifiant_Collaborateur":"CERFRANCE Finist\\u00e8re"}\],.......

------------ If I am Parsing it with JObject.Parse :

{
"Matricule_Collaborateur": "455",
"Nom_Prenom_Collaborateur": "lastname_455 firstname_455",
"Jour_Presence": "01-12-2022",
"Adresse_Postale_Collaborateur": "",
"Code_Postal_Collaborateur": "",
"Ville_Collaborateur": "",
"Date_Naissance_Collaborateur": "01-01-1980",
"Titre_Collaborateur": null,
"Email_Pro_Collaborateur": "email_455",
"Identifiant_Collaborateur": "CERFRANCE Finistère"
}
\],
\[
{
"Matricule_Collaborateur": "455",
"Nom_Prenom_Collaborateur": "lastname_455 firstname_455",
"Jour_Presence": "02-12-2022",
"Adresse_Postale_Collaborateur": "",
"Code_Postal_Collaborateur": "",
"Ville_Collaborateur": "",
"Date_Naissance_Collaborateur": "01-01-1980",
"Titre_Collaborateur": null,
"Email_Pro_Collaborateur": "email_455",
"Identifiant_Collaborateur": "CERFRANCE Finistère"
}
\],
\[
{
"Matricule_Collaborateur": "455",
"Nom_Prenom_Collaborateur": "lastname_455 firstname_455",
"Jour_Presence": "05-12-2022",
"Adresse_Postale_Collaborateur": "",
"Code_Postal_Collaborateur": "",
"Ville_Collaborateur": "",

......

------------ Here my Class :

public class PresenceDay
{
    //Properties
    [JsonPropertyName("Matricule_Collaborateur")]
     public string? Matricule { get; set; }

    [JsonPropertyName("Nom_Prenom_Collaborateur")]
    public string? Nom_Prenom { get; set; }

    [JsonPropertyName("Jour_Presence")]
    public string? Jour_Presence { get; set; }

    [JsonPropertyName("Adresse_Postale_Collaborateur")]
    public string? Adresse_Postale { get; set; }

    [JsonPropertyName("Code_Postal_Collaborateur")]
    public string? Code_Postal { get; set; }

    [JsonPropertyName("Ville_Collaborateur")]
    public string? Ville { get; set; }

    [JsonPropertyName("Date_Naissance_Collaborateur")]
    public string? Date_Naissance { get; set; }

    [JsonPropertyName("Titre_Collaborateur")]
    public string? Titre_Poste { get; set; }

    [JsonPropertyName("Email_Pro_Collaborateur")]
    public string? Email_Pro { get; set; }

    [JsonPropertyName("Identifiant_Collaborateur")]
    public string? Identifiant_Collaborateur { get; set; }
}

------------ Here my Program.cs :

try
{
Console.WriteLine("--------------------");
Console.WriteLine("Resultat API Jours de Présence :");
Console.WriteLine("--------------------");

            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
                NumberHandling = JsonNumberHandling.AllowReadingFromString
            };
            List<PresenceDay> obj_day = JsonSerializer.Deserialize<List<PresenceDay>>(result_day, options);
            //Console.WriteLine(obj_day);

            foreach (var day in obj_day)
            {
                Console.WriteLine(day);
                Console.WriteLine(day.Matricule);

            }

        }

(No compilation errors here)

catch(Exception ex)
{
Console.WriteLine("--------------------");
Console.WriteLine($"{ex}");
Console.WriteLine("--------------------");
Console.WriteLine("Resultat : ERREUR ");
Console.WriteLine("--------------------");
}

------------ An I get that :

--------------------
Resultat API Jours de Présence :
--------------------

System.Text.Json.JsonException: The JSON value could not be converted to System.Collections.Generic.List`1[Cf29.TicketRestos.Entities.PresenceDay]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.    at System.Text.Json.ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(Type propertyType)    at System.Text.Json.Serialization.JsonCollectionConverter`2.OnTryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, TCollection& value)
at System.Text.Json.Serialization.JsonConverter`1.TryRead(Utf8JsonReader& reader, Type typeToConvert, JsonSerializerOptions options, ReadStack& state, T& value)    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 jsonTypeInfo, Nullable`1 actualByteCount)
at System.Text.Json.JsonSerializer.ReadFromSpan\[TValue\](ReadOnlySpan\`1 json, JsonTypeInfo jsonTypeInfo)
at System.Text.Json.JsonSerializer.Deserialize\[TValue\](String json, JsonSerializerOptions options)
at Cf29.TicketRestos.Program.Main(String\[\] args) in C:\\Users\\1643\\source\\repos\\Cf29.TicketRestos\\Cf29.TicketRestos\\Program.cs:line 84
--------------------
Resultat : ERREUR
--------------------

Hope you can help me

Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • That's not valid JSON. JSON doesn't escape square brackets. Test what you posted in any JSON validator, you'll get an error. – Panagiotis Kanavos Jan 25 '23 at 11:27
  • If we ignore the escaped square brackets (`\[`) one thing that seems off to me is the double square brackets (`\[\[`). That would imply you are for some reason receiving a collection of collections of `PresenceDay`. It should look like this `[ { object 1 }, { object2 }, ...]`. – noel Jan 25 '23 at 12:09
  • Yes it is. My JSON is in an array in an array. That is the problem and I do not know how to do to fix it. – Lucie LE COZ Jan 25 '23 at 12:23

2 Answers2

0

Your JSON is broken. It's not JSON. Instead of \[ it should be [ and closing brackets likewise.

There is nothing a parser can do for you, if you feed it broken JSON.

You need to fix your data.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • It is the copy/paste. I sware my JSON is alright.. – Lucie LE COZ Jan 25 '23 at 12:01
  • Can you simplify it a little bit? What is the JSON you try to parse with the line `JsonSerializer.Deserialize>(result_day, options)` ? Because your JSON is just not an array of Elements. – nvoigt Jan 25 '23 at 12:33
  • I try to deserialize my var result_day. result_day is my JSON response (the first code above) I am not working with my parse JSON the second code above) I just put it here to help to read the first JSON information.. – Lucie LE COZ Jan 25 '23 at 12:57
  • Well, there you have your problem. You are trying to deserialize a list of elements. Your JSON **is not** a list of elements. Simple as that. – nvoigt Jan 25 '23 at 12:57
  • If you want to deserialize only *parts* of your JSON, you have to get that part. Or deserialize the whole JSON as the element it is. – nvoigt Jan 25 '23 at 12:58
0

your json is not valid, I fixed it at first

json = json.Replace("\\[\\[","[").Replace("\\]","]");
var jsonObject = JsonObject.Parse(json);

var options = new JsonSerializerOptions
{
        PropertyNameCaseInsensitive = true,
        NumberHandling = JsonNumberHandling.AllowReadingFromString
};
List<PresenceDay> obj_day = jsonObject["data"].AsArray().Deserialize<List<PresenceDay>>(options);
Serge
  • 40,935
  • 4
  • 18
  • 45
  • Thank you Serge for your answer. Finally I made 2 foreach on my Parse Json and I obtain my object. It is not the best way but it's working !! Thank you for all of you guys ! – Lucie LE COZ Jan 26 '23 at 10:17