1

How do I convert a Json String with multiple Objects to java objects:

EDIT:It would seem unlikely that it would work, yet would this create 2 class instances of class Statement:

String JsonStr = "{\"bills\":[{\"amount\":\"13\",\"billId\":\"billid3\"}] ,\"bills\":[{\"amount\":\"155\",\"billId\":\"billid4\"}]}";
ObjectMapper mapper = new ObjectMapper();
Statement obj = mapper.readValue(JsonStr, obj.class);

If not, how do I write the code for a program that receives a JSON String with multiple unique objects of the same type(bank statement), and create the appropriate number of java object instances of it? I would greatly appreciate any help.

Thanks so much!

3
  • Isn't there a typo in the code snippet? Your String isn't surrounded by quotes. Commented Nov 4, 2016 at 2:44
  • 1
    Yeah, sorry i didn't place much attention on that part.. Considering those 3 lines are java runnable Commented Nov 4, 2016 at 2:51
  • You could potentially get array of bills. Do you expect something different? Commented Nov 4, 2016 at 7:49

2 Answers 2

2

I think the json string you provided should be like

"{\"bills\":[{\"amount\":\"13\",\"billId\":\"billid3\"} ,{\"amount\":\"155\",\"billId\":\"billid4\"}]}"

If this is the case, you can use the solution below:

Create two classes Bill.java and TestObject.java as follows:

Bill.java

public class Bill {
    private double amount;
    private String billId;
    /**
     * @return the amount
     */
    public double getAmount() {
        return amount;
    }
    /**
     * @param amount the amount to set
     */
    public void setAmount(double amount) {
        this.amount = amount;
    }
    /**
     * @return the billId
     */
    public String getBillId() {
        return billId;
    }
    /**
     * @param billId the billId to set
     */
    public void setBillId(String billId) {
        this.billId = billId;
    }

}

TestObject.java

import java.util.List;

public class TestObject {

    private List<Bill> bills;

    /**
     * @return the bills
     */
    public List<Bill> getBills() {
        return bills;
    }

    /**
     * @param bills the bills to set
     */
    public void setBills(List<Bill> bills) {
        this.bills = bills;
    }

}

Here is the main program to test the code.

Test.java

import com.fasterxml.jackson.databind.ObjectMapper;

public class Test {

    public static void main(String[] args) {
        String jsonStr = "{\"bills\":[{\"amount\":\"13\",\"billId\":\"billid3\"} ,{\"amount\":\"155\",\"billId\":\"billid4\"}]}";

        ObjectMapper mapper = new ObjectMapper();
        try {
            TestObject testObject = mapper.readValue(jsonStr, TestObject.class);
            System.out.print(testObject);
        } catch (Exception e) {
            e.printStackTrace();
        } 
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks so much. Your code made me realize how Jackson's mapper automatically takes care of object creation. Although it seems on my end there still seems to be an error of the type:"Unrecognized field "bills" (Class sample.TestObject), not marked as ignorable". If you know how to solve this it would be greatly appreciated1
1

I have used gson-2.2.2.jar.

Please find code given below :

Bill.java

public class Bill
{
    private double  billAmount;

    private String  billId;

    //getters and setters
}

Main.java

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class Main
{
    public static void main(String[] args)
    {
        Bill bill = null;
        List<Bill> bills = new ArrayList<Bill>();
        for (int i = 0; i < 5; i++)
        {
            bill = new Bill();
            bill.setBillAmount(100 + (i + 1));
            bill.setBillId("bill_id_" + (i + 1));
            bills.add(bill);
        }
        Gson gson = new Gson();
        String json = gson.toJson(bills, new TypeToken<List<Bill>>()
        {}.getType());
        System.out.println(json);

        Type mapType = new TypeToken<List<Bill>>()
        {}.getType();
        List<Bill> billsRetrieved = new Gson().fromJson(json, mapType);
        for (Bill bill2 : billsRetrieved)
        {
            System.out.println(bill2.getBillId());
        }
    }
}

OutPut :

[
   {
      "billAmount":101.0,
      "billId":"bill_id_1"
   },
   {
      "billAmount":102.0,
      "billId":"bill_id_2"
   },
   {
      "billAmount":103.0,
      "billId":"bill_id_3"
   },
   {
      "billAmount":104.0,
      "billId":"bill_id_4"
   },
   {
      "billAmount":105.0,
      "billId":"bill_id_5"
   }
]

bill_id_1 bill_id_2 bill_id_3 bill_id_4 bill_id_5

Please revert in case you need further explanation.

1 Comment

This wasn't exactly what I wanted, but introduced me to Gson which seems very useful. I would surely make use of it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.