Gson - extract data from array - (known field value)

Hi guys
I’m really struggling here and could do with some help. Im just learning JAVA as i go and hav got a bit stuck.
I’m trying to extract from the json below the full element where i know one of the field values but after hours of reading im none the wiser.

So from this:

{
"name": "My Group",
"groupId": "5c7d64783c570522afb151b5-5c7d64783c570522afb151b6",
"devices": [{
		"deviceId": "5c7d64783c570522afb151b5-2-3157331848+1",
		"name": "Kitchen Socket",
		"productCode": "L42",
		"product": "L42",
		"device": "socket",
		"desc": "Smart Socket",
		"type": "lwrfTwoWay_v2",
		"cat": "Power",
		"gen": 2
	},
	{
		"deviceId": "5c7d64783c570522afb151b5-3-3157331848+1",
		"name": "Washing Machine",
		"productCode": "L42",
		"product": "L42",
		"device": "socket",
		"desc": "Smart Socket",
		"type": "lwrfTwoWay_v2",
		"cat": "Power",
		"gen": 2
    }]}

I want to get all the fields where i know the deviceId using gson such as:

Device deviceStatus = gson.fromJson(Response.getJson(), Device.class);

however i dont know how to search based on the deviceId and return only that array.
in JSONPath i would do:

$.devices[?(@.deviceId.indexOf('5c7d64783c570522afb151b5-2-3157331848+1') != -1)]

to get the first element

Take a look at the Java Stream API, specifically the filter method.
https://www.google.com/search?q=java+stream+filter

Basically… Define a class to represent the entire json object (i.e. Group), making sure you represent the array of devices as a List (i.e. List<Device> devices;). Then use fromJson to parse the entire object using Group.class. Then you can use the Stream API filter method on the devices list to get the device you want.

1 Like