0

I have the following String code and I want to convert to json and iterate through items and put them into an arraylist in Java. I also have a class called Users whith its attributes and getters/setters(id, nick, age, online, avatar)how should i do:

code:

//this is the real code
String a = "{"id":"1","nick":"jhon","age":20,"online":1,"avatar":"http:\/\/www.example.com\/image.jpeg"},{"id":"2","nick":"mike","age":45,"online":0,"avatar":"http:\/\/www.example.com\/image.jpeg"},{"id":"3","nick":"carl","age":12,"online":1,"avatar":"http:\/\/www.example.com/image.jpeg"},{"id":"4","nick":"ana","age":22,"online":0,"avatar":"http:\/\/www.example.com\/image.jpeg"}";


//this is what i want to do
String a = real code sample;
Json b = a.toJson; // something like this
Arraylist<User> list = new Arraylist<User>();
for each b{
     list.add(     new user(b.getId(),b.getNick()....));
}

i want to do something like that and of course the code is an example and here it's not well written.

Damian SIlvera
  • 866
  • 1
  • 9
  • 19

3 Answers3

0

You may prefer to use Gson library which has good documentation for how to use. You can easly parse objects to JSON and JSON to object. So it may be a better alternative for your own parser.

It also supports Arrays and Collections.

bhdrkn
  • 6,244
  • 5
  • 35
  • 42
0

I think you need to validate you array first on JSONLINT

Rahul P
  • 1,065
  • 3
  • 17
  • 32
0

Jackson is quite nice for this sort of thing - I've been using it for some time with no problems. I've heard nice things about Gson as well, but had no reason to switch from Jackson. Xstream also can work with Json.

Instead of working with a special "JSON" object, Jackson (and I believe Gson as well) stuff the JSON values into a POJO. You use the annotations to customize how the values are read and written.

FWIW, JSON processing is easy with a library like this, but also something you don't want to do much - it's relatively expensive in terms of CPU. It's not that the libs are slow - that kind of text processing is a lot of work.

Will Iverson
  • 2,009
  • 12
  • 22