Si vous pouvez choisir n'importe quelle bibliothèque JSON, Jackson est un bon choix.
Voici une démonstration de Jackson en action pour résoudre le problème présenté à l'origine.
import java.util.ArrayList;
import java.util.List;
import org.codehaus.jackson.map.ObjectMapper;
public class JacksonDemo
{
public static void main(String[] args) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
List<ProductFromServiceTemp> products = getListFromWebservice();
String json = mapper.writeValueAsString(products);
System.out.println(json);
}
private static List<ProductFromServiceTemp> getListFromWebservice()
{
List<ProductFromServiceTemp> productList = new ArrayList<ProductFromServiceTemp>();
for (int i = 0; i < 10; i++)
{
ProductFromServiceTemp product = new ProductFromServiceTemp();
product.setName("name " + i);
product.setDescription("desc " + i);
product.setPrice(i * 100d);
productList.add(product);
}
return productList;
}
}
class ProductFromServiceTemp
{
private String name;
private String description;
private double price; // Don't use double type for financial information.
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getDescription() {return description;}
public void setDescription(String description) {this.description = description;}
public double getPrice() {return price;}
public void setPrice(double price) {this.price = price;}
}
La sortie JSON
[
{
"name": "name 0",
"description": "desc 0",
"price": 0
},
{
"name": "name 1",
"description": "desc 1",
"price": 100
},
{
"name": "name 2",
"description": "desc 2",
"price": 200
},
{
"name": "name 3",
"description": "desc 3",
"price": 300
},
{
"name": "name 4",
"description": "desc 4",
"price": 400
},
{
"name": "name 5",
"description": "desc 5",
"price": 500
},
{
"name": "name 6",
"description": "desc 6",
"price": 600
},
{
"name": "name 7",
"description": "desc 7",
"price": 700
},
{
"name": "name 8",
"description": "desc 8",
"price": 800
},
{
"name": "name 9",
"description": "desc 9",
"price": 900
}
]