function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Carlos Manuel Lozano SotoCarlos Manuel Lozano Soto 

Parse String Json "_id" to "id" Apex Object

Hi guys,
¿How can I parse a string json with a complex attribute name "_id"?

I'm trying to parse the next json:

 

[{"_id":"55d66226726b611100aaf741","replacement":false,"quantity":5,"name":"Generator 1000 kW","maintenanceperiod":365,"lifespan":120,"cost":5000,"sku":"100003"},{"_id":"55d66226726b611100aaf742","replacement":true,"quantity":183,"name":"Cooling Fan","maintenanceperiod":0,"lifespan":0,"cost":300,"sku":"100004"}]
The Class that I created is:
 
public class Equipment {
    public final String id;
    public final Boolean replacement;
    public final Integer quantity;
    public final String name;
    public final Integer maintenanceperiod;
    public final Integer lifespan;
    public final Integer cost;
    public final Integer sku;

    public Equipment(String id, Boolean replacement, Integer quantity, String name, Integer maintenanceperiod, Integer lifespan, Integer cost, Integer sku) {
        this.id = id;
        this.replacement = replacement;
        this.quantity = quantity;
        this.name = name;
        this.maintenanceperiod = maintenanceperiod;
        this.lifespan = lifespan;
        this.cost = cost;
        this.sku = sku;
    }
}

But I'm having troubles to parse _id from origin string json to Apex code.
 
System.assertEquals('55d66226726b611100aaf741', equipments.get(0).id);

When I try to get the id, only I can obtain null value.

Thanks for your time.
Best Regards, 
Carlos Lozano.

 
Best Answer chosen by Carlos Manuel Lozano Soto
Carlos Manuel Lozano SotoCarlos Manuel Lozano Soto
As a result, I was applying the next code to replace "_id" for "id", but I think there must be a better solution.
 
public static List<Equipment> jsonToListEquipment(String stringJson){
        String replaced = stringJson.replaceAll('\"_id\"', '\"id\"');
        return (List<Equipment>) JSON.deserialize(replaced, List<Equipment>.class);
    }

 

All Answers

Carlos Manuel Lozano SotoCarlos Manuel Lozano Soto
As a result, I was applying the next code to replace "_id" for "id", but I think there must be a better solution.
 
public static List<Equipment> jsonToListEquipment(String stringJson){
        String replaced = stringJson.replaceAll('\"_id\"', '\"id\"');
        return (List<Equipment>) JSON.deserialize(replaced, List<Equipment>.class);
    }

 
This was selected as the best answer
yob ecom359yob ecom359
thank you for this awesome comment for learning more about it See Here