简体   繁体   中英

Android Json Parsing with multipartEntity

I need to parse this as an JsonArray instead of objects but it dosent seem to work correctly.

my output is ["{"TransactionVolume":"34","TransactionitemID":"2"}"]

I need it to be [{"TransactionVolume":"34","TransactionitemID":"2"}]

this is part of my code

public class TransactionItem {

    public String TransactionitemID;
    public String TransactionVolume;

    public String getTransactionVolume() {
        return TransactionVolume;
    }

    public void setTransactionVolume(String transactionVolume) {
        TransactionVolume = transactionVolume;
    }

    public String getTransactionitemID() {
        return TransactionitemID;
    }

    public void setTransactionitemID(String transactionitemID) {
        TransactionitemID = transactionitemID;
    }


}

TransactionItem transactionItem = new TransactionItem();
transactionItem.setTransactionitemID(article.toString());
transactionItem.setTransactionVolume(volume.toString());


 String transitemjson = gson.toJson(transactionItem);
 JSONArray ja = new JSONArray();
 ja.put(transitemjson);
 String test = ja.toString().replaceAll("\\\\\"", "\"");

Ja seems to be right where the output is

["{\\"TransactionVolume\\":\\"34\\",\\"TransactionitemID\\":\\"2\\"}"]

So I've tried to replace all \\ with " but still the " at the begging and end.

Trimming the String doesn't seem like an good idea, but it could work. Is there any other way of doing this?

EDIT

This got me to the goal!

 ArrayList<TransactionItem> Transactionlist = new ArrayList<>();

        for (int i=0; i < CompleteArticle.size(); i++) {
          String id = CompleteArticle.get(i);
          String Volume = CompleteVolume.get(i);
            TransactionItem transactionItem = new TransactionItem();
            transactionItem.setTransactionitemID(id);
            transactionItem.setTransactionVolume(Volume);
            //transactionitems.transactionitems.add(transactionItem);
            Transactionlist.add(transactionItem);
        }


  JsonElement transitemjson = gson.toJsonTree(transactionItems);

Output :

[{"TransactionVolume":"1","TransactionitemID":"5"},{"TransactionVolume":"3","TransactionitemID":"3"}]

You need to use a JSONElement instead of a String . Replace this line:

String transitemjson = gson.toJson(transactionItem);

With this:

JSONElement transitemjson = gson.toJsonTree(transactionItem);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM