Search code examples
javaandroidjsonclassparcelable

How to convert Java Class and Java Array List to JSON


I have a Java class and I want to convert it to JSON so I can POST it to WCF Service

Here an Example of what I'm looking for:

            Invoice invoice = new Invoice();

            InvoiceMaster IM = new InvoiceMaster();
            IM.setClientId(SelectedClient.getId());
            IM.setDate("2016-01-01");
            IM.setTypeId(1);
            IM.setOrderedBy("abc");
            invoice.setHeader(IM);

            InvoiceDetail ID;
            List<InvoiceDetail> IDs = new ArrayList<>();
            for (OrderItem I : items) {
                ID = new InvoiceDetail();
                ID.setItemId(I.getItemId());
                ID.setQty(I.getQuantity());
                ID.setUnitPrice(I.getUnitPrice());
                ID.setTotalPrice(I.getTotalPrice());
                ID.setNotes("");
                ID.setUnitId(0);
                IDs.add(ID);
            }
            invoice.setDetails(IDs);

        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("Invoice", invoice);


      //Code to Debug the result ------
        String json = jsonObject.toString();
        Log.d("ABC:",json);
      //------------------------------

the result is like following {"Invoice":"com.technoplusplus.distribution.Classes.Invoice@3960a129"}

Invoice is Parcelable and also the Invoice.Header is Java class (InvoiceMaster is Parcelable) and Invoice.Details is List of Java Class (InvoiceDetail class is Parcelable)

Thanks


Solution

  • just do this (Gson from google)

    Gson gson = new Gson();
    String json = gson.toJson(invoice);