2012-05-23 7 views
5

Estoy tratando de convertir varios objetos del mismo tipo en un List en Java. Por ejemplo, mi JSON sería:¿Cómo convierto una matriz JSON en una lista de Java? Estoy usando svenson

{ 
    "Example": [ 
     { 
      "foo": "a1", 
      "bar": "b1", 
      "fubar": "c1" 
     }, 
     { 
      "foo": "a2", 
      "bar": "b2", 
      "fubar": "c2" 
     }, 
     { 
      "foo": "a3", 
      "bar": "b3", 
      "fubar": "c3" 
     } 
    ] 
} 

tengo una clase:

public class Example { 
    private String foo; 
    private String bar; 
    private String fubar; 
    public Example(){}; 
    public void setFoo(String f){ 
     foo = f; 
    } 
    public void setBar(String b){ 
     bar = b; 
    } 
    public void setFubar(String f){ 
     fubar = f; 
    } 
... 
} 

Quiero ser capaz de convertir la cadena JSON de entrar en una lista de objetos Example. Me gustaría hacer algo como esto:

JSONParser parser = new JSONParser(); 
parser.addTypeHint(".Example[]", Example.class); 
List<Example> result = parser.parse(List.class, json); 

Hacer esto me da un error:

Cannot set property Example on class java.util.ArrayList 
+1

@Ted Hopp: Gracias por crear/agregar la etiqueta svenson. – Boundless

Respuesta

3

No es posible convertir este JSON a List pero se puede convertir esto en Map.
Ver su JSON String:

... 
"Example": [ 
     { 
      "foo": "a1", 
      "bar": "b1", 
      "fubar": "c1" 
     }, 
     { 
      "foo": "a2", 
      "bar": "b2", 
      "fubar": "c2" 
     }, 
     ... 
] 
} 

aquí "Ejemplo" es clave (cadena) y el valor es objeto de lista del ejemplo.

Prueba esto:

parser.addTypeHint("Example[]", Example.class); 
Map<String,List<Example>> result1 = parser.parse(Map.class, json); 
for (Entry<String, List<Example>> entry : result1.entrySet()) { 
    for (Example example : entry.getValue()) { 
      System.out.println("VALUE :->"+ example.getFoo()); 
    } 
} 

código completo de Example:

import java.util.List; 
import java.util.Map; 
import java.util.Map.Entry; 

import org.svenson.JSONParser; 

public class Test { 
    public static void main(String[] args) { 
     JSONParser parser = new JSONParser(); 
     parser.addTypeHint(".Example[]", Example.class); 
     String json = "{" + "\"Example\": [" + "{" + "\"foo\": \"a1\"," 
       + "\"bar\": \"b1\"," + "\"fubar\": \"c1\"" + "}," + "{" 
       + "\"foo\": \"a2\"," + "\"bar\": \"b2\"," + "\"fubar\": \"c2\"" 
       + "}," + "{" + "\"foo\": \"a3\"," + "\"bar\": \"b3\"," 
       + "\"fubar\": \"c3\"" + "}" + "]" + "}\""; 
     parser.addTypeHint("Example[]", Example.class); 
     Map<String, List<Example>> result1 = parser.parse(Map.class, json); 
     for (Entry<String, List<Example>> entry : result1.entrySet()) { 
      for (Example example : entry.getValue()) { 
       System.out.println("VALUE :->" + example.getFoo()); 
      } 
     } 
    } 
} 

public class Example { 
    private String foo; 
    private String bar; 
    private String fubar; 
    public Example(){} 
    public void setFoo(String foo) { 
     this.foo = foo; 
    } 
    public String getFoo() { 
     return foo; 
    } 
    public void setBar(String bar) { 
     this.bar = bar; 
    } 
    public String getBar() { 
     return bar; 
    } 
    public void setFubar(String fubar) { 
     this.fubar = fubar; 
    } 
    public String getFubar() { 
     return fubar; 
    } 
} 

OutPut:

VALUE :->a1 
VALUE :->a2 
VALUE :->a3 
+0

Gracias por la respuesta. Esto no está funcionando. Cuando llega a la línea: for (Ejemplo de ejemplo: entry.getValue()) {Recibo el siguiente error: java.util.HashMap no se puede convertir a com.xxx.Ejemplo – Boundless

+0

@Boundless - impossible.I update full ejemplo de código Acabo de responderte por qué y dónde estuvo mal. gracias –

+0

Gracias, esto funciona perfecto. No estoy seguro de cuál era el problema antes, pero esto funciona según sea necesario. – Boundless

4

Lo resuelto modificando mi JSON para estar en forma :

[ 
    { 
     "foo": "a1", 
     "bar": "b1", 
     "fubar": "c1" 
    }, 
    { 
     "foo": "a2", 
     "bar": "b2", 
     "fubar": "c2" 
    }, 
    { 
     "foo": "a3", 
     "bar": "b3", 
     "fubar": "c3" 
    } 
] 

Luego utiliza el código de Java:

JSONParser parser = new JSONParser(); 
    ArrayList list = parser.parse(ArrayList.class, json); 
    List<Example> result = new ArrayList<Example>(); 
    for(int i = 0 ; i < list.size() ; i++){ 
     HashMap<String, String> map = (HashMap) list.get(i); 
     Example example = new Example(); 
     example.setFoo(map.get("foo")); 
     example.setBar(map.get("bar")); 
     example.setFubar(map.get("fubar")); 
     result.add(example); 
    } 
1

tengo un jsonString así:

[ 
{"author":"amahta","bookId":1,"bookName":"name"}, 
{"author":"amahta2","bookId":2,"bookName":"name2"} 
] 

y convertirlo en una lista por este fragmento de código:

List<BookVO> listdata = new ArrayList<BookVO>(); 

JSONArray jArray = JSONArray.fromObject(booklist); 
if (jArray != null) { 
    for (int i = 0; i < jArray.size(); i++) { 
     JSONObject obj = JSONObject.fromObject(jArray.get(i)); 
     listdata.add(new BookVO(Long.valueOf(obj.get("bookId")), obj.get("bookName"), obj.get("author"))); 
    } 
} 

uso el archivo jar net.sf.json-lib.

0
 String paymentMethod = "[{\"paymentType\":\"google_iap\",\"msisdn\":1486890084928,\"operator\":\"maroc_ma\",\"paymentMethod\":\"maroc_ma\",\"reactivationEnabled\":true }]"; 

    PaymentMethod mop = null; 
     try { 
      mop = mapper.readValue(paymentMethod, PaymentMethod.class); 
     } catch (Exception e) { 
      logger.warn("Error while parsing paymentMethod = " + paymentMethod + " \n" + e); 
     } 

    List<PaymentMethod> result = new ArrayList<PaymentMethod>(); 
    result.add(mop); 

    billingInfo.setPaymentMethods(result); 
+1

Esto sería más útil si también agregó comentarios o una descripción sobre cómo esto resuelve el problema, en lugar de simplemente colocar un muro de código. – Xaniff

Cuestiones relacionadas