Error reading jobject from jsonreader current jsonreader item is not an object startarray

I am working on a Windows Phone 8.1 application involving location. I am receiving Json data from my API. My API returns data that looks like: [{ "country": "India", "city": "Mall Road, Gu...

I am working on a Windows Phone 8.1 application involving location. I am receiving Json data from my API. My API returns data that looks like:

[{
    "country": "India",
    "city": "Mall Road, Gurgaon",
    "area": "Haryana",
    "PLZ": "122002",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 77.08972334861755,
    "lat": 28.47930118040612,
    "formatted_address": "Mall Road, Gurgaon 122002, Haryana, India"
},
{
    "country": "India",
    "city": "Mall Road, Kanpur",
    "area": "Uttar Pradesh",
    "PLZ": "208004",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 80.35783410072327,
    "lat": 26.46026740300029,
    "formatted_address": "Mall Road, Kanpur 208004, Uttar Pradesh, India"
},
{
    "country": "India",
    "city": "Mall Road Area, Amritsar",
    "area": "Punjab",
    "PLZ": "143001",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 74.87286686897278,
    "lat": 31.64115178002094,
    "formatted_address": "Mall Road Area, Amritsar 143001, Punjab, India"
},
{
    "country": "India",
    "city": "Vasant Kunj (Mall Road Kishan Garh), New Delhi",
    "area": "Delhi",
    "PLZ": "110070",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "18",
    "phone": "",
    "lng": 77.1434211730957,
    "lat": 28.51363217008815,
    "formatted_address": "Vasant Kunj (Mall Road Kishan Garh), New Delhi 110070, Delhi, India"
}]

I am deserializing my Json data and putting it into a class named LocationData. When I run my code, it gives me an error:

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

Where am I going wrong? Here is my code:

private async void GetAPIData()
    {
        string _serviceUrl = "https://api.myweblinkapiprovider/v2&q=" + UserRequestedLocation;
        HttpClient client = new HttpClient();

        HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));

        if (responce.Content != null)
        {
            var respArray = JObject.Parse(await responce.Content.ReadAsStringAsync());
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            var rcvdData = JsonConvert.DeserializeObject<LocationData>(respArray.ToString(), settings);
            UpdateMapData(rcvdData);
            UpdateTextData(rcvdData);
        }
    }

I also tried to use a JArray. My code is as below:

 private async void GetAPIData()
    {
        string _serviceUrl = "https://api.myweblinkprovider.com/v3?fun=geocode&lic_key=MyKey" + UserRequestedLocation;
        HttpClient client = new HttpClient();

        HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));

        JArray arr = JArray.Parse(await responce.Content.ReadAsStringAsync());

        foreach (JObject obj in arr.Children<JObject>())
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr.ToString(), settings);
            UpdateMapData(rcvdData);
            UpdateTextData(rcvdData);
        }
    }

It also gives me an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MMI_SpeechRecog.Model.LocationData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

First I made an application and then I’ve started doing test for it ( Know it is not good way ), everything works fine with parsing etc, but after i made few test got an error :

Newtonsoft.Json.JsonReaderException : Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path », line 1, position 1.

Error occurs there jObject = JObject.Parse(content); and there arrayList = JArray.Parse(content);

internal JObject DoParse(string content)
{
    JObject jObject = new JObject();
    if (content != null)
    {
        if (content.Contains("Unable"))
        {
            MessageBox.Show("Not found.", "Error");
        }
        else
        {
            jObject = JObject.Parse(content);
        }
    }
    return jObject;
}

internal JArray DoParseOnList(string content)
{
    JArray arrayList = new JArray();
    if (content != null)
    {
        if (content.Contains("Unable"))
        {
            MessageBox.Show("Not found.", "Error");
        }
        else
        {

            arrayList = JArray.Parse(content);
        }
    }
    else { }
    return arrayList;
}

Any ideas what is wrong ?
Btw. string content is json which i got from the server.
Thanks in advance !

JSON

Test Name:  SetGroup
Test Outcome:   Failed
Result Message: SetUp : Newtonsoft.Json.JsonReaderException : Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Result StandardOutput:  [{"id":6208,"name":"test"},{"id":6315,"name":"jPOD v144 Testing"},{"id":6306,"name":"iButton Issue"},{"id":6424,"name":"Hybrid"}]
[{"id":6208,"name":"test"},{"id":6315,"name":"jPOD v144 Testing"},{"id":6306,"name":"iButton Issue"},{"id":6424,"name":"Hybrid"}]
[{"enabled":true,"scriptVersion":199,"configVersion":3,"name":"LMU3030 Hybrid Car Test based on 64.112 add ignition on-off"},{"enabled":true,"scriptVersion":199,"configVersion":2,"name":"LMU3030 Hybrid Car Test based on 50.106"},{"enabled":true,"scriptVersion":199,"configVersion":1,"name":"Hybrid car LMU 3030 Ignition test","description":""},{"enabled":true,"scriptVersion":64,"configVersion":113,"name":"based on 64.112 Engineering Build from calamp"},{"enabled":true,"scriptVersion":61,"configVersion":106},{"enabled":true,"scriptVersion":38,"configVersion":117},{"enabled":true,"scriptVersion":184,"configVersion":0},{"enabled":true,"scriptVersion":13,"configVersion":54},{"enabled":true,"scriptVersion":23,"configVersion":105,"name":"PULS Redirect to PROD","description":"Changes just Param 2320 to maint.vehicle-location.com"}]
[]
[{"message":"Not Implemented","vbusDeviceFiles":[],"vbusFileHistories":[]}]

  • Remove From My Forums
  • Question

  • User565442435 posted

    I’m trying to parse a simple JSON string
    [{«url»:»http://loyalty.bosselman.com/Home/tabid/57/Default.aspx»,»position»:»0″,»roles»:»All Users;Administrators;»}]

    You can find it here

    http://loyalty.bosselman.com/DesktopModules/MyServices/API/Welcome/GetMenu?key

    When I run this code

                var baseUrl = "http://loyalty.bosselman.com/DesktopModules/MyServices/API/Welcome/GetMenu?key";
    
                WebClient client = new WebClient();
                var data = client.DownloadString(baseUrl);
    
    
                var obj = JsonConvert.DeserializeObject(data);
    
                JObject job = JObject.Parse(obj.ToString());
    
                foreach (JProperty prop in job.Properties())
                {
                    Response.Write(prop["url"]);
                }

    I get this error

    Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path », line 1, position 1.

    If I inspect my obj element it looks like this

    «[{«url»:»http://loyalty.bosselman.com/Home/tabid/57/Default.aspx»,»position»:»0″,»roles»:»All Users;Administrators;»}]»

    I’m not sure why the » are getting in there and obj.replace(«\», «»); does not remove them. What am I doing wrong?

Answers

  • User565442435 posted

    I tried every form of jobject, jarray, deserialize I could think of. Ended up just changing my web service to deliver xml because I needed to get it done.

    • Marked as answer by

      Thursday, October 7, 2021 12:00 AM

Hi I am passing the below string in my code in line var json = JObject.Parse(jStr); and I get the error as

System.Private.CoreLib: Exception while executing function: Function1.
Newtonsoft.Json: Error reading JObject from JsonReader. Current
JsonReader item is not an object: StartArray.

Can someone please explain me how should I fix this. Is it because it is an array kind? At the end my passed string will be an array. how can I fix this?. here is the sample string(one object from the array) which I am passing in above line

[
  {
    "_id": "_AUQ9",
    "im:SiceErrors": {
      "errors": [
        {
          "_id": "O9UQ9_0",
          "ErrorMessage": "Uype",          
          "Parameter": "r:type",
          "ParameterValue": "[n  "~:bbl:P924",n  "~:corer:ag"n]",
          "RefObjectParameter": "type_key",
          "Project": "NPOS+1"
        }
      ]
    },
    "cullad-tag:Cject": "P|GT",
    "bbl:P1014": "PIGT",
    "cullad-tag:MoomosBaseObjectDescription": "Gate Valve",
    "bbl:P3935": "Gve",
    "cullad-tag:CreateDate": "15.10.2021",
    "cullad-tag:MoomosDescription": "P2",
    "cullad-tag:MoomosUID": "A49",
    "bbl:011772": "UQ9",
    "cullad-tag:Description": "P2",
    "cullad-tag:Discipline": "U",
    "bbl:P101001445": "bbl:P163",
    "cullad-tag:FLabel": "FFeed",
    "bbl:P1094": "pd:P1299",   
    "bbl:P10791": "V",
    "cullad-tag:FutureTag": "No",
    "cullad-tag:IndexType": "MV",
    "bbl:P138": "bbl:P1563",
    "cullad-tag:IsTopTag": "No",
    "bbl:P7": "No",
    "cullad-tag:MountedOn": "F-18UD800",
    "bbl:P4024": "F-18800",   
    "bbl:P1834": "pd:P1094",    
    "bbl:P1803": "8120",
    "cullad-tag:SubProjectCategory": "Feed",
    "cullad-tag:SubProjectName": "SUB",
    "cullad-tag:System": "18",
    "bbl:P01660": "bbl:P15326",
    "cullad-tag:TagNumber": "F-120",
    "bbl:P10022": "F-20",   
    "cdf:type": [
      "bbl:P10924",
      "bbl:P101907",
      "bbl:P101003632",
      "bbl:P13932",
      "bbl:P21",
      "iso15926:InanimatePject",
      "iso15926:Object",
      "Moomos:PopoFeedTag"
    ],
    "primarycdf:type": "bbl:P924"
  }
]

>Solution :

Your example is a single object inside an array.

@SeeSharp propose to wrap that array.

The opposite way is, if that’s always the case, that you can just parse the object inside that array (removing first and last character):

var json = JObject.Parse(jStr.Remove(str.Length - 1).Remove(0, 1));

Otherwise, I guess you just adapt your code to handle an array, and not an object (which looks the better way to do so)

EDIT :

Since there is multiple object inside your JArray, just iterate over it :

foreach (JObject item in JArray.Parse(jStr)) 
{
  DoStuffOnJObject(item) // call your method
}

Posted By: Anonymous

I am working on a Windows Phone 8.1 application involving location. I am receiving Json data from my API. My API returns data that looks like:

[{
    "country": "India",
    "city": "Mall Road, Gurgaon",
    "area": "Haryana",
    "PLZ": "122002",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 77.08972334861755,
    "lat": 28.47930118040612,
    "formatted_address": "Mall Road, Gurgaon 122002, Haryana, India"
},
{
    "country": "India",
    "city": "Mall Road, Kanpur",
    "area": "Uttar Pradesh",
    "PLZ": "208004",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 80.35783410072327,
    "lat": 26.46026740300029,
    "formatted_address": "Mall Road, Kanpur 208004, Uttar Pradesh, India"
},
{
    "country": "India",
    "city": "Mall Road Area, Amritsar",
    "area": "Punjab",
    "PLZ": "143001",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "17",
    "phone": "",
    "lng": 74.87286686897278,
    "lat": 31.64115178002094,
    "formatted_address": "Mall Road Area, Amritsar 143001, Punjab, India"
},
{
    "country": "India",
    "city": "Vasant Kunj (Mall Road Kishan Garh), New Delhi",
    "area": "Delhi",
    "PLZ": "110070",
    "street": "",
    "house_no": "",
    "POI": "",
    "type": "18",
    "phone": "",
    "lng": 77.1434211730957,
    "lat": 28.51363217008815,
    "formatted_address": "Vasant Kunj (Mall Road Kishan Garh), New Delhi 110070, Delhi, India"
}]

I am deserializing my Json data and putting it into a class named LocationData. When I run my code, it gives me an error:

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

Where am I going wrong? Here is my code:

private async void GetAPIData()
    {
        string _serviceUrl = "https://api.myweblinkapiprovider/v2&q=" + UserRequestedLocation;
        HttpClient client = new HttpClient();

        HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));

        if (responce.Content != null)
        {
            var respArray = JObject.Parse(await responce.Content.ReadAsStringAsync());
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            var rcvdData = JsonConvert.DeserializeObject<LocationData>(respArray.ToString(), settings);
            UpdateMapData(rcvdData);
            UpdateTextData(rcvdData);
        }
    }

I also tried to use a JArray. My code is as below:

 private async void GetAPIData()
    {
        string _serviceUrl = "https://api.myweblinkprovider.com/v3?fun=geocode&lic_key=MyKey" + UserRequestedLocation;
        HttpClient client = new HttpClient();

        HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));

        JArray arr = JArray.Parse(await responce.Content.ReadAsStringAsync());

        foreach (JObject obj in arr.Children<JObject>())
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;
            var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr.ToString(), settings);
            UpdateMapData(rcvdData);
            UpdateTextData(rcvdData);
        }
    }

It also gives me an error:

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'MMI_SpeechRecog.Model.LocationData' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.

Solution

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn’t the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can’t say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you’re passing it (denoted by the opening [ in your API response). This is what the «StartArray» in the error message is telling you.

As for what happened when you used JArray, you’re using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I’d be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren’t going to use the parsed version separately, it’s best to avoid it.

Answered By: Anonymous

Related Articles

  • Combining items using XSLT Transform
  • Geofire query events not firing
  • Multiple markers Google Map API v3 from array of addresses…
  • Instance member can’t be accessed using static access
  • send value from ember component to parent template
  • How to update the props for a child component in Vue.js?
  • Seperation of streetname and housenumber
  • How to merge/ add columns to dataframes in pandas when the…
  • How to update google-maps-react direction route?
  • Polymer v1.0 iron-list distance calculation as each item is…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
{
    "result": {
        "230968023": {
            "icon_url": "W_I_5GLm4wPcv9jJQ7z7tz_l_0sEIYUhRfbF4arNQkgGQGKd3kMuVpMgCwRZrg-fckaVmPtFa-_fPQY2FZOxF0a-NaiPx0vyWoYQIoc0bz9AhIzrg00QBijXDLdCANArvs-Shwy5Dh3RJ2URl3QA-A",
            "icon_url_large": "W_I_5GLm4wPcv9jJQ7z7tz_l_0sEIYUhRfbF4arNQkgGQGKd3kMuVpMgCwRZrg-fckaVmPtFa-_fPQY2FZPASkWvM6jDw0v0XohCf9Y8bj4b3dm9gxsTXHDSDeAXXIEjvMmShgrtCVeZfDA-n5JB3KTzdw2wPA",
            "icon_drag_url": "",
            "name": "Inscribed Whalehook",
            "market_hash_name": "Inscribed Whalehook",
            "market_name": "Inscribed Whalehook",
            "name_color": "CF6A32",
            "background_color": "",
            "type": "Immortal weapon",
            "tradable": "1",
            "marketable": "1",
            "commodity": "0",
            "market_tradable_restriction": "7",
            "market_marketable_restriction": "7",
            "fraudwarnings": "",
            "descriptions": {
                "0": {
                    "type": "html",
                    "value": "Used By: Pudge",
                    "app_data": ""
                },
                "1": {
                    "type": "html",
                    "value": "Ideally, a hook made for reeling in enormous creatures of the deep would not gouge and hack into the bones and flesh of the prey. But Pudge doesn't much care if he makes a mess of his meat.",
                    "app_data": ""
                }
            },
            "tags": {
                "0": {
                    "internal_name": "strange",
                    "name": "Inscribed",
                    "category": "Quality",
                    "color": "CF6A32",
                    "category_name": "Quality"
                },
                "1": {
                    "internal_name": "Rarity_Immortal",
                    "name": "Immortal",
                    "category": "Rarity",
                    "color": "e4ae39",
                    "category_name": "Rarity"
                },
                "2": {
                    "internal_name": "wearable",
                    "name": "Wearable",
                    "category": "Type",
                    "category_name": "Type"
                },
                "3": {
                    "internal_name": "weapon",
                    "name": "Weapon",
                    "category": "Slot",
                    "category_name": "Slot"
                },
                "4": {
                    "internal_name": "npc_dota_hero_pudge",
                    "name": "Pudge",
                    "category": "Hero",
                    "category_name": "Hero"
                }
            },
            "classid": "230968023"
        },
        "success": true
    }
}

Edit time: 2017-05-10. Add a method to transform list
First, I know a way to parse JSON string before, I find it a little troublesome. I got another one from somewhere else

string json = vlt.getlist();

JObject jo = JObject.Parse(json);

var data = jo.getValue("data").ToObject<T>();

T is the corresponding entity class, and can be used directly in the member variable data.member
2. Json transformation of the List is to put it into redIS cache, and then take it out for transformation
Don’t talk nonsense, code on:

            var t = new List<PcWareListByCourseId>();
            var m1 = new PcWareListByCourseId
            {
                videoId = 12,
                IsAuditions = false,
                percent = 23,
                practiceId = 43,
                statuss = 2,
                TotalTime = "12.2",
                wareId = 22,
                wareName = "courseware"
            };
            var m2 = new PcWareListByCourseId
            {
                videoId = 12,
                IsAuditions = false,
                percent = 23,
                practiceId = 43,
                statuss = 2,
                TotalTime = "12.2",
                wareId = 22,
                wareName = "courseware"
            };
            t.Add(m1);
            t.Add(m2);
            RedisInfoHelper.SetRedis("test",t);

            var get = RedisInfoHelper.GetRedisValue("test");

            var jo = JArray.Parse(get);
            var jj = jo.ToObject<List<PcWareListByCourseId>>();

Entity code:

    public class PcWareListByCourseId
    {
        public int wareId { set; get; }
        public string wareName { set; get; }
        public bool IsAuditions { set; get; }
        public int videoId { set; get; }
        public int percent { set; get; }
        public int practiceId { set; get; }
        public int statuss { set; get; }
        public string TotalTime { set; get; }//11'22"
    }



Successful to the last step, successful transformation.
This time I’m using the JArray method class.

Read More:

Понравилась статья? Поделить с друзьями:
  • Error reading influxdb status code 401
  • Error reading imagelist bitmap failed to read imagelist data from stream
  • Error reading from tunnel http socket
  • Error project zomboid снизу справа
  • Error reading from source device