2012-05-23 6 views
5

Sto provando a convertire più oggetti dello stesso tipo in uno List in Java. Ad esempio, il mio JSON sarebbe:Come convertire un array JSON in un elenco Java. Sto usando svenson

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

Ho una classe:

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; 
    } 
... 
} 

voglio essere in grado di trasformare la stringa JSON mi trovo in una lista di Example oggetti. Mi piacerebbe fare qualcosa di simile:

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

In questo modo si ottiene un errore:

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

@Ted Hopp: Grazie per aver creato/aggiunto il tag svenson. – Boundless

risposta

3

Non è possibile convertire questo JSON per List ma è possibile convertire questo per Map.
vedere il tuo JSON String:

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

Qui "Esempio" è la chiave (String) e il valore è oggetto Lista dell'esempio.

Prova questo:

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()); 
    } 
} 

codice completo di 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

Grazie per la risposta. Questo non funziona Quando arriva alla riga: for (Esempio di esempio: entry.getValue()) {Viene visualizzato il seguente errore: java.util.HashMap non può essere trasmesso a com.xxx.Example – Boundless

+0

@Boundless - impossibile.Io aggiornamento completo esempio di codice. Ti ho appena risposto perché e dove era sbagliato. grazie –

+0

Grazie, questo funziona perfettamente. Non sono sicuro di quale fosse il problema prima, ma funziona come necessario. – Boundless

4

ho risolto modificando il mio JSON per essere in forma :

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

Poi ho usato il codice 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

ho un jsonstring come questo:

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

e convertirlo in un elenco da questo frammento di codice:

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"))); 
    } 
} 

utilizzo il file 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

Questo sarebbe più utile se hai aggiunto anche commenti o una descrizione su come questo risolva il problema, piuttosto che mettere semplicemente un muro di codice. – Xaniff

Problemi correlati