0

I wrote a restService and my service returns me two different result :

{"Response": {
"cars":[
{"id":"1",
"name":"test1"},
{"id":"2",
"name":"test2"},
{"id":"3",
"name":"test3"}
],
"books":[
{"id":"4",
"name":"example1"},
{"id":"5",
"name":"example2"},
{"id":"6",
"name":"example3"}    
]}}

and second ,

{"Response": {
"cars":{
"id":"1",
"name":"test1"},
"books":{
"id":"4",
"name":"example1"}
}}

I will show the result in my dataTable with javascript. For this, I want to learn length of cars or books. If result >1 I can get length, cars or books act as an array,but if result <1 it acts as an object and I can't get length of objects .In my restService, I defined as an ArrayList the cars and books. Is there any solutions for this ? Thanks for responses.

Ozkan Ciftci
  • 89
  • 1
  • 11
  • `var len = Array.isArray(Response.cars) ? Response.cars.length : 1` – adeneo Sep 17 '14 at 15:15
  • @adeneo I tried this but when I write `Response.cars[i]` in a for loop, it can't show to me because of it is a object – Ozkan Ciftci Sep 17 '14 at 15:44
  • Look closely, `Array.isArray(Response.cars)` <- that's how you know it's an array, if that fails, it's not an array, so you don't do a `for` loop at all. – adeneo Sep 17 '14 at 15:52
  • Thanks @adeneo, yes you are right , it is a solution to learn it's an array or not,I'm sure it is an array, and I want to do a for loop at all. – Ozkan Ciftci Sep 17 '14 at 16:21

1 Answers1

3

The problem lies with your REST Service, make it always return a list of cars, even if there is only one car.

folkol
  • 4,752
  • 22
  • 25
  • I've also seen lots of examples of returning a "count" variable with your JSON, just to make it easier to work with. – jsuddsjr Sep 17 '14 at 15:17
  • Yes, that is unfortunately pretty common. My personal opinion is that metadata like that does not belong in a JSON response. Either use an array for that data, or pass the metadata in a separate structure. (Or use XML and pass the count as an attribute, if you want to be able to read it without parsing the full structure) – folkol Sep 17 '14 at 15:20
  • @folkol but my REST Service returns list of Response, not list of cars ? – Ozkan Ciftci Sep 17 '14 at 15:48
  • Yes, but I was talking about the value called "cars", make sure that it is always a list, even when there is only one car (Or no cars for that matter). – folkol Sep 17 '14 at 15:49
  • `List cars= new ArrayList(); cars= result.getSelectedCars(); Response.setCars(cars);` I think you want to say like this , but it did not work – Ozkan Ciftci Sep 17 '14 at 16:16
  • What API do you use for serialization? I think that old Jackson libraries tried to be smart about empty or single element lists. – folkol Sep 17 '14 at 16:41
  • I didn't notice , I'll search this, thanks for response @folkol – Ozkan Ciftci Sep 18 '14 at 10:24