简体   繁体   中英

How to convert JSON array to java object

This is the json i'm sending via POST request

{
  "PIds" : [ "MOB123", "ELEC456"]
}

This is my class that receives the JSON,

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/GetProductsInfo")
public List<ProductDetails> getProductsInfo(ProductIds productIds) {

    System.out.println(productIds + "   ");

    DBCursor<ProductDetails> dbCursor = collection.find(DBQuery.in("pid", productIds.getPIds()));

    List<ProductDetails> products = new ArrayList<>();
    while (dbCursor.hasNext()) {
        ProductDetails product = dbCursor.next();
        products.add(product);
    }
    return products;
}

Im converting the JSON array into the 'ProductIds' object, this is my POJO class

public class ProductIds
{
    @JsonProperty("PIds")
    private List<String> pIds;

    public List<String> getPIds()
    {
        return pIds;
    }

    public void setPIds(List<String> Pids)
    {
        this.pIds = Pids;
    }

    @Override
    public String toString()
    {
        return "ClassPojo [PIds = "+ pIds +"]";
    }
}

The problem for me here is that the JSON is not getting populated into the java object 'productIds' is NULL, I dont know why. Im new to Jackson can someone help me out. Thank you

Are you using JAXB? Jersey? fasterxml.jackson? I'm getting the impression you are using several at the same time

RestClass:

@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Path("/GetProductsInfo")
public List<ProductDetails> getProductsInfo(@RequestBody ProductIds productIds) {
   // etc
}

For JAXB:

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ProductIds {
    @XmlElement("PIds")
    private List<String> pIds;

    public List<String> getPIds() {
        return pIds;
    }

    public void setPIds(List<String> Pids) {
        this.pIds = Pids;
    }

    @Override
    public String toString() {
        return "ClassPojo [PIds = " + pIds + "]";
    }
}

Otherwise take a look at:

Convert a JSON string to object in Java ME?

How to convert the following json string to java object?

Did you try to get the ID's out using .getJSONArray()? Uses the org.json library.

JSONObject obj = new JSONObject(jsoninput);

JSONArray jsonArray = obj.getJSONArray("PIds");

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