Json / Apex:为Json数组上的节点分配值

时间:2016-06-28 05:18:11

标签: json salesforce apex

我有一个定义JSON结构的顶点代码。我想寻求有关如何使用Apex为JSON上的字符串字段赋值的建议。 JSON将有一个数组(PackageData),其中包含应包含值

的字段

Apex代码:

public class Shipment{
    public PackageData[] PackageData;
}

public class PackageData{
    public Packaging Packaging;
    public Dimensions Dimensions;
    public PackageWeight PackageWeight;
}

public class Packaging{
    public string Code;
}

public class Dimensions{
    public UnitOfMeasurement UnitOfMeasurement;
    public string Length;
    public string Width;
    public string Height;
}

public class UnitOfMeasurement{
    public string Code;
}

public class PackageWeight{
    public UOM UOM;
    public string Weight;
}

public class UOM{
    public string Code;
}

JSON:

{
    "PackageData": [
        {
            "Packaging": {
                "Code": ""
            },
            "Dimensions": {
                "UnitOfMeasurement": {
                    "Code": ""
                },
                "Length": "",
                "Width": "",
                "Height": ""
            },
            "PackageWeight": {
                "UOM": {
                    "Code": ""
                },
                "Weight": ""
            }
        }   
    ]
}

1 个答案:

答案 0 :(得分:1)

JSON 总是字符串,所以有一个解析器将对象解析为 JSON字符串,反之亦然

Parser完成它的工作并自动解析为 String ,你不用担心

Json to Object:

ClassName objName = (ClassName) System.JSON.deserialize(jsonString, ClassName.class);

Json的对象:

String jsonString = System.JSON.serialize(objName);