Search code examples
apiparsingresponseodooxml-rpc

How can I parse xmlrpc response (Odoo API read), using Java


I have to fetch the category a product is related to, using the read method of Odoo API. I get a list of objects, then for each category, I need to extract the field product_tmpl_ids, a list of integers. I'm not sure how to do it. This is the method:

public List readModelfields(String modelName, List<Integer> ids, List<String> fields, Integer uid) throws XmlRpcException {
    List record = (List) Arrays.asList((Object[]) models.execute("execute_kw", Arrays.asList(
            db, uid, password,
            modelName, "read",
            ids,
            new HashMap() {{
                put("fields", fields);
            }}
    )));
    return record;
}

This is the rest of the code:

List<String> fields = new ArrayList<>();
fields.add("product_tmpl_ids");
List categoryIds = (List<Integer>)service.searchByStrParameter("product.public.category", "name", "A - Administration / Office", uid);
List result = (List)service.readModelfields("product.public.category", categoryIds, fields, uid);

Can anybody help? How to extract the fields from the fetched objects?


Solution

  • You passed the result of the search method (a list) to readModelfields which is used as-is to call read method, as documented in External API read method ids must be passed in a list:

    Arrays.asList(ids),
    

    You used search followed with the read method on the same model, you can use search_read instead.

    The following example shows how to fetch the many2many field category_id of res.partners

    public List searchReadModelfields(String modelName, List domain, List<String> fields, Integer uid) throws XmlRpcException {
        return (List)Arrays.asList((Object[])models.execute("execute_kw", Arrays.asList(
                db, uid, password,
                modelName,
                "search_read",
                Arrays.asList(domain),
                new HashMap() {{
                    put("fields", fields);
                }}
        )));
    }
    

    Call searchReadModelfields and print out the values:

    List<String> fields = new ArrayList<>();
    fields.add("category_id");
    List domain = Arrays.asList(
            Arrays.asList("category_id", "!=", false)
    );
    
    // return list of hashmaps)
    List result = (List)service.searchReadModelfields("res.partner", domain, fields, uid);
    
    HashMap values;
    Integer partner_id;
    Object[] category_ids;
    for(Object partner_data: result) {
        values  = (HashMap)partner_data;
        partner_id = (Integer) values.get("id");
        category_ids = (Object [])values.get("category_id");
    
        System.out.printf("{partner_id: %s, ", partner_id);
        System.out.print("category_ids:[");
        for(Object category_id: category_ids) {
            System.out.printf("%s,",
                    category_id
            );
        }
        System.out.println("]}");
     }