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
Alex MakkAlex Makk 

Json to Apex: How to process dynamic keys?

Hi everyone!

I'm having the following JSON:
 
{
	"log": {
		"id": 776812465,
		"date": "2022-02-25",
		"vehicles": [
			{
				"vehicle": {
					"id": 112334,
					"number": "308 R"
				}
			},
			{
				"vehicle": {
					"id": 112337,
					"number": "#309",

				}
			}
		],
		"odometers": {
			"#309": [
				{
					"end": 83810,
					"start": 83810,
					"metric_units": false
				},
				{
					"end": 83823,
					"start": 83810,
					"metric_units": false
				}
			],
			"308 R": [
				{
					"end": 194414,
					"start": 194310,
					"metric_units": false
				},
				{
					"end": 194487,
					"start": 194414,
					"metric_units": false
				}
			]
		}
	}
}

I used JSON to APEX tool to get wrapper class:
 
public class fromJSON{
	public cls_log log;
	class cls_log {
		public Integer id;	//776812465
		public String date;	//2022-02-25
		public cls_vehicles[] vehicles;
		public cls_odometers odometers;
	}
	class cls_vehicles {
		public cls_vehicle vehicle;
	}
	class cls_vehicle {
		public Integer id;	//112334
		public String number;	//308 R
	}
	class cls_odometers {
		public cls_#309[] #309;
		public cls_308 R[] 308 R;
	}
	class cls_#309 {
		public Integer end;	//83810
		public Integer start;	//83810
		public boolean metric_units;
	}
	class cls_308 R {
		public Integer end;	//194414
		public Integer start;	//194310
		public boolean metric_units;
	}
	public static fromJSON parse(String json){
		return (fromJSON) System.JSON.deserialize(json, fromJSON.class);
	}
}

The problem I'm facing is that vehicle numbers under odometers will be always different. So I can't have something like:
public cls_#309[] #309;
public cls_308 R[] 308 R;
Please advise how I can process this dynamically via wrapper class. Thank you!
 
John Pipkin 14John Pipkin 14
Alex, 

To do this, you can use a Map. Like so
public class fromJSON{
	public cls_log log;
	class cls_log {
		public Integer id;	//776812465
		public String date;	//2022-02-25
		public cls_vehicles[] vehicles;
		public Map<String, List<cls_odometer>> odometers;
	}
	class cls_vehicles {
		public cls_vehicle vehicle;
	}
	class cls_vehicle {
		public Integer id;	//112334
		public String number;	//308 R
	}
	class cls_odometer {
		public Integer end;	
		public Integer start;	
		public boolean metric_units;
	}
	public static fromJSON parse(String json){
		return (fromJSON) System.JSON.deserialize(json, fromJSON.class);
	}
}

Hope that helps!