How to use JsonOutput class of org.openqa.selenium.json package

Best Selenium code snippet using org.openqa.selenium.json.JsonOutput

Run Selenium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

copy
1// Licensed to the Software Freedom Conservancy (SFC) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The SFC licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18package org.openqa.grid.web.servlet;
19
20import static org.openqa.selenium.json.Json.MAP_TYPE;
21
22import com.google.common.collect.ImmutableMap;
23
24import org.openqa.grid.common.exception.GridException;
25import org.openqa.grid.internal.ExternalSessionKey;
26import org.openqa.grid.internal.GridRegistry;
27import org.openqa.grid.internal.RemoteProxy;
28import org.openqa.grid.internal.TestSession;
29import org.openqa.selenium.json.Json;
30import org.openqa.selenium.json.JsonException;
31import org.openqa.selenium.json.JsonInput;
32import org.openqa.selenium.json.JsonOutput;
33
34import java.io.BufferedReader;
35import java.io.IOException;
36import java.io.InputStreamReader;
37import java.io.Reader;
38import java.io.Writer;
39import java.util.HashMap;
40import java.util.Map;
41import java.util.TreeMap;
42
43import javax.servlet.http.HttpServletRequest;
44import javax.servlet.http.HttpServletResponse;
45
46public class TestSessionStatusServlet extends RegistryBasedServlet {
47
48  private final Json json = new Json();
49
50  public TestSessionStatusServlet() {
51    super(null);
52  }
53
54  public TestSessionStatusServlet(GridRegistry registry) {
55    super(registry);
56  }
57
58  @Override
59  protected void doGet(HttpServletRequest request, HttpServletResponse response)
60      throws IOException {
61    Map<String, Object> json = ImmutableMap.of(
62        "session", request.getParameter("session"));
63    process(response, json);
64  }
65
66  @Override
67  protected void doPost(HttpServletRequest request, HttpServletResponse response)
68      throws IOException {
69    Map<String, Object> requestJSON = new HashMap<>();
70    if (request.getInputStream() != null) {
71      try (Reader rd = new BufferedReader(new InputStreamReader(request.getInputStream()));
72           JsonInput jin = json.newInput(rd)) {
73        requestJSON = jin.read(MAP_TYPE);
74      }
75    }
76    process(response, requestJSON);
77  }
78
79  protected void process(HttpServletResponse response, Map<String, Object> requestJson)
80      throws IOException {
81    response.setContentType("application/json");
82    response.setCharacterEncoding("UTF-8");
83    response.setStatus(200);
84    try (Writer writer = response.getWriter();
85         JsonOutput out = json.newOutput(writer)) {
86      out.write(getResponse(requestJson));
87    } catch (JsonException e) {
88      throw new GridException(e.getMessage());
89    }
90  }
91
92  private Map<String, Object> getResponse(Map<String, Object> requestJson) {
93    Map<String, Object> res = new TreeMap<>();
94    res.put("success", false);
95
96    // the id can be specified via a param, or in the json request.
97    String session;
98    if (!requestJson.containsKey("session")) {
99      res.put(
100          "msg",
101          "you need to specify at least a session or internalKey when call the test slot status service.");
102      return res;
103    }
104      session = String.valueOf(requestJson.get("session"));
105
106    TestSession testSession = getRegistry().getSession(ExternalSessionKey.fromString(session));
107
108    if (testSession == null) {
109      res.put("msg", "Cannot find test slot running session " + session + " in the registry.");
110      return res;
111    }
112    res.put("msg", "slot found !");
113    res.remove("success");
114    res.put("success", true);
115    res.put("session", testSession.getExternalKey().getKey());
116    res.put("internalKey", testSession.getInternalKey());
117    res.put("inactivityTime", testSession.getInactivityTime());
118    RemoteProxy p = testSession.getSlot().getProxy();
119    res.put("proxyId", p.getId());
120    return res;
121  }
122}
123
Full Screen
copy
1EvalClassName[] evalClassName;
2ArrayList<EvalClassName> list;
3evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
4list = new ArrayList<>(Arrays.asList(evalClassName));
5
Full Screen
copy
1val jsonArrayString = "['A','B','C']"
2
3val gson = Gson()
4
5val listType: Type = object : TypeToken<List<String?>?>() {}.getType()
6
7val stringList : List<String> = gson.fromJson(
8                            jsonArrayString,
9                            listType)
10
Full Screen
copy
1[
2      {
3           id : '1',
4           title: 'sample title',
5           ....
6      },
7      {
8           id : '2',
9           title: 'sample title',
10           ....
11     },
12      ...
13 ]
14
Full Screen
copy
1 Gson gson=new GsonBuilder().create();
2                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));
3
Full Screen
copy
1val fileData = "your_json_string"
2val gson = GsonBuilder().create()
3val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
4
Full Screen
copy
1/**
2 * Convert JSON string to a list of objects
3 * @param sJson String sJson to be converted
4 * @param tClass Class
5 * @return List<T> list of objects generated or null if there was an error
6 */
7public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){
8
9    try{
10        Gson gson = new Gson();
11        List<T> listObjects = new ArrayList<>();
12
13        //read each object of array with Json library
14        JSONArray jsonArray = new JSONArray(sJson);
15        for(int i=0; i<jsonArray.length(); i++){
16
17            //get the object
18            JSONObject jsonObject = jsonArray.getJSONObject(i);
19
20            //get string of object from Json library to convert it to real object with Gson library
21            listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
22        }
23
24        //return list with all generated objects
25        return listObjects;
26
27    }catch(Exception e){
28        e.printStackTrace();
29    }
30
31    //error: return null
32    return null;
33}
34
Full Screen
copy
1Type listType = new TypeToken<List<Post>>() {}.getType();
2List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);
3
Full Screen
copy
1Gson gson=new Gson();
2ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
3
Full Screen
copy
1Gson gson=new Gson();
2Post [] refVar=gson.fromJson(jsonString,Post[].class);
3
Full Screen
copy
1List<Post> posts=(List<Post>)gson.fromJson(jsonString, 
2                     new TypeToken<List<Post>>(){}.getType());
3
Full Screen
copy
1import java.lang.reflect.ParameterizedType;
2import java.lang.reflect.Type;
3import java.util.ArrayList;
4import java.util.Collection;
5import java.util.Iterator;
6
7import com.google.gson.Gson;
8import com.google.gson.JsonArray;
9import com.google.gson.JsonDeserializationContext;
10import com.google.gson.JsonDeserializer;
11import com.google.gson.JsonElement;
12import com.google.gson.JsonParseException;
13
14public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
15
16    @Override
17    public Collection<?> deserialize(JsonElement json, Type typeOfT,
18            JsonDeserializationContext context) throws JsonParseException {
19        Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
20
21        return parseAsArrayList(json, realType);
22    }
23
24    /**
25     * @param serializedData
26     * @param type
27     * @return
28     */
29    @SuppressWarnings("unchecked")
30    public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
31        ArrayList<T> newArray = new ArrayList<T>();
32        Gson gson = new Gson();
33
34        JsonArray array= json.getAsJsonArray();
35        Iterator<JsonElement> iterator = array.iterator();
36
37        while(iterator.hasNext()){
38            JsonElement json2 = (JsonElement)iterator.next();
39            T object = (T) gson.fromJson(json2, (Class<?>)type);
40            newArray.add(object);
41        }
42
43        return newArray;
44    }
45
46}
47
Full Screen
copy
1public class JSONParsingTest {
2
3    List<World> worlds;
4
5    @Test
6    public void grantThatDeserializerWorksAndParseObjectArrays(){
7
8        String worldAsString = "{\"worlds\": [" +
9            "{\"name\":\"name1\",\"id\":1}," +
10            "{\"name\":\"name2\",\"id\":2}," +
11            "{\"name\":\"name3\",\"id\":3}" +
12        "]}";
13
14        GsonBuilder builder = new GsonBuilder();
15        builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
16        Gson gson = builder.create();
17        Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
18
19        assertNotNull(decoded);
20        assertTrue(JSONParsingTest.class.isInstance(decoded));
21
22        JSONParsingTest decodedObject = (JSONParsingTest)decoded;
23        assertEquals(3, decodedObject.worlds.size());
24        assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
25    }
26}
27
Full Screen
copy
1public class World {
2    private String name;
3    private Long id;
4
5    public void setName(String name) {
6        this.name = name;
7    }
8
9    public String getName() {
10        return name;
11    }
12
13    public Long getId() {
14        return id;
15    }
16
17    public void setId(Long id) {
18        this.id = id;
19    }
20
21}
22
Full Screen
copy
1Gson gson = new Gson();
2String jsonOutput = "Your JSON String";
3Type listType = new TypeToken<List<Post>>(){}.getType();
4List<Post> posts = gson.fromJson(jsonOutput, listType);
5
Full Screen
copy
1EvalClassName[] evalClassName;
2ArrayList<EvalClassName> list;
3evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
4list = new ArrayList<>(Arrays.asList(evalClassName));
5
Full Screen
copy
1val jsonArrayString = "['A','B','C']"
2
3val gson = Gson()
4
5val listType: Type = object : TypeToken<List<String?>?>() {}.getType()
6
7val stringList : List<String> = gson.fromJson(
8                            jsonArrayString,
9                            listType)
10
Full Screen
copy
1[
2      {
3           id : '1',
4           title: 'sample title',
5           ....
6      },
7      {
8           id : '2',
9           title: 'sample title',
10           ....
11     },
12      ...
13 ]
14
Full Screen
copy
1 Gson gson=new GsonBuilder().create();
2                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));
3
Full Screen
copy
1val fileData = "your_json_string"
2val gson = GsonBuilder().create()
3val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
4
Full Screen
copy
1/**
2 * Convert JSON string to a list of objects
3 * @param sJson String sJson to be converted
4 * @param tClass Class
5 * @return List<T> list of objects generated or null if there was an error
6 */
7public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){
8
9    try{
10        Gson gson = new Gson();
11        List<T> listObjects = new ArrayList<>();
12
13        //read each object of array with Json library
14        JSONArray jsonArray = new JSONArray(sJson);
15        for(int i=0; i<jsonArray.length(); i++){
16
17            //get the object
18            JSONObject jsonObject = jsonArray.getJSONObject(i);
19
20            //get string of object from Json library to convert it to real object with Gson library
21            listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
22        }
23
24        //return list with all generated objects
25        return listObjects;
26
27    }catch(Exception e){
28        e.printStackTrace();
29    }
30
31    //error: return null
32    return null;
33}
34
Full Screen
copy
1Type listType = new TypeToken<List<Post>>() {}.getType();
2List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);
3
Full Screen
copy
1Gson gson=new Gson();
2ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
3
Full Screen
copy
1Gson gson=new Gson();
2Post [] refVar=gson.fromJson(jsonString,Post[].class);
3
Full Screen
copy
1List<Post> posts=(List<Post>)gson.fromJson(jsonString, 
2                     new TypeToken<List<Post>>(){}.getType());
3
Full Screen
copy
1import java.lang.reflect.ParameterizedType;
2import java.lang.reflect.Type;
3import java.util.ArrayList;
4import java.util.Collection;
5import java.util.Iterator;
6
7import com.google.gson.Gson;
8import com.google.gson.JsonArray;
9import com.google.gson.JsonDeserializationContext;
10import com.google.gson.JsonDeserializer;
11import com.google.gson.JsonElement;
12import com.google.gson.JsonParseException;
13
14public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
15
16    @Override
17    public Collection<?> deserialize(JsonElement json, Type typeOfT,
18            JsonDeserializationContext context) throws JsonParseException {
19        Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
20
21        return parseAsArrayList(json, realType);
22    }
23
24    /**
25     * @param serializedData
26     * @param type
27     * @return
28     */
29    @SuppressWarnings("unchecked")
30    public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
31        ArrayList<T> newArray = new ArrayList<T>();
32        Gson gson = new Gson();
33
34        JsonArray array= json.getAsJsonArray();
35        Iterator<JsonElement> iterator = array.iterator();
36
37        while(iterator.hasNext()){
38            JsonElement json2 = (JsonElement)iterator.next();
39            T object = (T) gson.fromJson(json2, (Class<?>)type);
40            newArray.add(object);
41        }
42
43        return newArray;
44    }
45
46}
47
Full Screen
copy
1public class JSONParsingTest {
2
3    List<World> worlds;
4
5    @Test
6    public void grantThatDeserializerWorksAndParseObjectArrays(){
7
8        String worldAsString = "{\"worlds\": [" +
9            "{\"name\":\"name1\",\"id\":1}," +
10            "{\"name\":\"name2\",\"id\":2}," +
11            "{\"name\":\"name3\",\"id\":3}" +
12        "]}";
13
14        GsonBuilder builder = new GsonBuilder();
15        builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
16        Gson gson = builder.create();
17        Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
18
19        assertNotNull(decoded);
20        assertTrue(JSONParsingTest.class.isInstance(decoded));
21
22        JSONParsingTest decodedObject = (JSONParsingTest)decoded;
23        assertEquals(3, decodedObject.worlds.size());
24        assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
25    }
26}
27
Full Screen
copy
1public class World {
2    private String name;
3    private Long id;
4
5    public void setName(String name) {
6        this.name = name;
7    }
8
9    public String getName() {
10        return name;
11    }
12
13    public Long getId() {
14        return id;
15    }
16
17    public void setId(Long id) {
18        this.id = id;
19    }
20
21}
22
Full Screen
copy
1Gson gson = new Gson();
2String jsonOutput = "Your JSON String";
3Type listType = new TypeToken<List<Post>>(){}.getType();
4List<Post> posts = gson.fromJson(jsonOutput, listType);
5
Full Screen
copy
1 objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
2
Full Screen
copy
1import com.fasterxml.jackson.core.JsonParseException;
2import com.fasterxml.jackson.databind.JsonMappingException;
3import com.fasterxml.jackson.databind.ObjectMapper;
4import java.util.HashMap;
5import java.util.Map;
6
7// Pretty-print the JSON result
8try {
9    ObjectMapper objectMapper = new ObjectMapper();
10    Map<String, Object> response = objectMapper.readValue(result, HashMap.class);
11    System.out.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(response));
12} catch (JsonParseException e) {
13    e.printStackTrace();
14} catch (JsonMappingException e) {
15    e.printStackTrace();
16} catch (IOException e) {
17    e.printStackTrace();
18} 
19
Full Screen
copy
1<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper">
2    <property name="dateFormat">
3        <bean class="java.text.SimpleDateFormat">
4            <constructor-arg value="yyyy-MM-dd" />
5            <property name="lenient" value="false" />
6        </bean>
7    </property>
8    <property name="serializationInclusion">
9        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">
10            NON_NULL
11        </value>
12    </property>
13</bean>
14
15<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
16    <property name="targetObject">
17        <ref bean="objectMapper" />
18    </property>
19    <property name="targetMethod">
20        <value>enable</value>
21    </property>
22    <property name="arguments">
23        <value type="com.fasterxml.jackson.databind.SerializationFeature">
24            INDENT_OUTPUT
25        </value>
26    </property>
27</bean>
28
Full Screen
copy
1val indentOutput = SerializationFeature.INDENT_OUTPUT
2val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
3defaultStateField.setAccessible(true)
4defaultStateField.set(indentOutput, true)
5
Full Screen
copy
1public static void main(String[] args) throws IOException {
2
3byte[] jsonBytes = Files.readAllBytes(Paths.get("C:\\data\\testfiles\\single-line.json"));
4
5ObjectMapper objectMapper = new ObjectMapper();
6
7Object json = objectMapper.readValue( jsonBytes, Object.class );
8
9System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString( json ) );
10}
11
Full Screen
copy
1new ObjectMapper()
2.writer()
3.withDefaultPrettyPrinter()
4.writeValueAsString(new HashMap<String, Object>());
5
Full Screen
copy
1System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonInstance));
2
Full Screen
copy
1System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(jsonInstance));
2
Full Screen
copy
1Gson gson = new GsonBuilder().setPrettyPrinting().create();
2String jsonOutput = gson.toJson(someObject);
3
Full Screen
copy
1mapper.enable(SerializationFeature.INDENT_OUTPUT);
2
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run Selenium Automation Tests on LambdaTest Cloud Grid

Trigger Selenium automation tests on a cloud-based Grid of 3000+ real browsers and operating systems.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)