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.

4
  • var len = Array.isArray(Response.cars) ? Response.cars.length : 1 Commented Sep 17, 2014 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 Commented Sep 17, 2014 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. Commented Sep 17, 2014 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. Commented Sep 17, 2014 at 16:21

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

7 Comments

I've also seen lots of examples of returning a "count" variable with your JSON, just to make it easier to work with.
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 but my REST Service returns list of Response, not list of cars ?
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).
List<Car> cars= new ArrayList<Car>(); cars= result.getSelectedCars(); Response.setCars(cars); I think you want to say like this , but it did not work
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.