Xamarin Android JSON反序列化报错:无法将JSON对象转为数组类型
Hey there, let's break down what's causing this error and fix it quickly.
The Root Cause
The error message spells it out clearly: your API is returning a single JSON object (structured like { "Office": "...", ... }), but your code is trying to deserialize it into a List<Galeri>—which expects a JSON array (structured like [{...}, {...}]). That mismatch is why you're getting the deserialization failure.
Solution 1: Adjust Code to Handle Single Object
If your API is only supposed to return one office entry (which seems to be the case here), modify your deserialization code to target a single Galeri instance instead of a list. Then, if your adapter needs a list to work with, just wrap the single object in a list:
RunOnUiThread(() => { // Deserialize to a single Galeri object first var singleGaleri = JsonConvert.DeserializeObject<Galeri>(e.Result); // Wrap it in a List to match your adapter's requirement itemGaleri = new List<Galeri> { singleGaleri }; CustomListAdapter adapter = new CustomListAdapter(this, itemGaleri); DaftarGaleri.Adapter = adapter; progress.Visibility = ViewStates.Gone; DaftarGaleri.ItemClick += DaftarGaleri_ItemClick; } );
Solution 2: Adjust API to Return an Array (If Needed)
If your API is supposed to return multiple office entries but is currently sending a single object, you'll need to update the backend to wrap the response in square brackets ([]) to make it a valid JSON array. For example:
[{"Office":"دكتور نيوترشن", "officename":"11111111", ...}]
This would let your original list deserialization code work as intended, but this requires changes to the API itself.
Quick Checks to Verify
- Log the raw
e.Resultvalue to your console to confirm the exact JSON structure from the API. - Note that your
Galericlass has amembertypeproperty which isn't present in the API response—Json.NET will ignore this missing field by default, so no extra work is needed here unless you require it to have a default value.
内容的提问来源于stack exchange,提问作者Mr.Balaha

