Example usage for com.google.gson Gson fromJson

List of usage examples for com.google.gson Gson fromJson

Introduction

In this page you can find the example usage for com.google.gson Gson fromJson.

Prototype

@SuppressWarnings("unchecked")
public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException 

Source Link

Document

This method deserializes the Json read from the specified parse tree into an object of the specified type.

Usage

From source file:burrito.links.JsonLinkParser.java

License:Apache License

/**
 * This method will attempt to parse the input string as JSON, and
 * return a {@link Link} object. If the referenced entity can not be
 * found, the return value is null./*from   ww w .  ja v  a2s.c  o m*/
 * 
 * If the string is not a valid JSON representation, the returned
 * {@link Link} object will instead contain the input string in it's
 * url field.
 * 
 * If the input value is null, the method returns null.
 * 
 * In other words, the input should be either a valid link JSON
 * string, or a URL, or null.
 * 
 * @param value
 * @return
 */
public Link parse(String value) {
    if (value == null) {
        return null;
    }

    Link link = new Link();
    String url = null;

    try {
        Gson gson = new Gson();
        LinkJsonOverlay overlay = gson.fromJson(value, LinkJsonOverlay.class);

        if (overlay.absoluteUrl != null) {
            url = overlay.absoluteUrl;
        } else {
            try {
                Class<?> clazz = Class.forName(overlay.typeClassName);
                Linkable linkable = (Linkable) Model.all(clazz).filter("id", overlay.typeId).get();

                if (linkable != null) {
                    url = linkable.getUrl();
                }
            } catch (ClassNotFoundException e) {
                // url remains null
            }
        }

        link.setTypeName(overlay.typeClassName);
        link.setId(overlay.typeId);
        link.setText(overlay.linkText);
    } catch (JsonParseException e) {
        url = value;

        link.setTypeName(LinkedEntityWidgetPopup.TYPE_ABSOLUTE_URL);
        link.setId(-1L);
        link.setText(value);
    }

    if (url == null) {
        return null;
    }

    link.setUrl(url);

    return link;
}

From source file:burrito.services.CrudServiceImpl.java

License:Apache License

private CrudField createEmbeddedListField(Class<?> type, List<String> jsonList) {
    List<CrudEntityDescription> descs = new ArrayList<CrudEntityDescription>();
    if (jsonList != null) {
        for (String embedded : jsonList) {
            Gson gson = new Gson();
            Object overlay = gson.fromJson(embedded, type);
            CrudEntityDescription desc = createEntityDescription(type.getName(), null, type, overlay);
            descs.add(desc);//w w  w.  j ava 2 s .c  o m
        }
    }
    @SuppressWarnings("unchecked")
    EmbeddedListField field = new EmbeddedListField(descs, ((Class<? extends Model>) type).getName());
    return field;
}

From source file:BusinessLogic.Controller.RestController.java

public List<Plan> getPlans() throws Exception {
    StringBuilder responseS = new StringBuilder();
    try {//w w w.  ja v  a 2 s . c o m
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("http://localhost:8080/JoyCenter/resources/plans");
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (IOException e) {
    }

    Gson gson = new Gson();
    List<Plan> planes = gson.fromJson(responseS.toString(), new TypeToken<List<Plan>>() {
    }.getType());

    return planes;

}

From source file:BusinessLogic.Controller.RestController.java

public Plan getPlan(int planId) throws Exception {
    StringBuilder responseS = new StringBuilder();
    try {//from  w  w w  .  j a va 2 s  .com
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("http://localhost/JoyCenter/resources/plans/" + planId);
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (IOException e) {
    }

    //Receive response, parse to POJO array.
    Gson gson = new Gson();
    return gson.fromJson(responseS.toString(), Plan.class);
}

From source file:BusinessLogic.Controller.RestController.java

public Plan updatePlan(Plan plan) throws Exception {
    StringBuilder responseS = new StringBuilder();

    try {/*from  w ww  .j  a v  a2s. c o m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://locahost/JoyCenter/resources/plans/" + plan.getId());

        Gson gson = new Gson();
        StringEntity input = new StringEntity(gson.toJson(plan));
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    Gson gson = new Gson();
    return gson.fromJson(responseS.toString(), Plan.class);

}

From source file:BusinessLogic.Controller.RestController.java

public List<Hotel> getHotels() throws Exception {
    StringBuilder responseS = new StringBuilder();

    try {//from   w ww. j  a  va2s.  com
        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpGet getRequest = new HttpGet("http://192.168.162.121/Hoex/hoexAPI/hoteles");
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }

        httpClient.getConnectionManager().shutdown();

    } catch (IOException e) {
    }

    Gson gson = new Gson();
    List<Hotel> hoteles = gson.fromJson(responseS.toString(), new TypeToken<List<Hotel>>() {
    }.getType());

    return hoteles;

}

From source file:BusinessLogic.Controller.RestController.java

public List<Viaje> getViajes() throws Exception {
    StringBuilder responseS = new StringBuilder();
    try {//from w w  w.  j a  v a2  s .c om
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet("http://192.168.162.167/Terminal/resources/viajes/");
        getRequest.addHeader("accept", "application/json");
        HttpResponse response = httpClient.execute(getRequest);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }
        httpClient.getConnectionManager().shutdown();
    } catch (IOException e) {
    }
    Gson gson = new Gson();
    List<Viaje> viajes = gson.fromJson(responseS.toString(), new TypeToken<List<Viaje>>() {
    }.getType());
    return viajes;
}

From source file:ca.cmput301f13t03.adventure_datetime.model.StoryDB.java

License:Open Source License

/**
 * Creates a StoryFragment from a cursor
 *
 * @param cursor A Cursor pointing to a StoryFragment
 *
 * @return A StoryFragment instance from the Database
 *//*from  w w w. jav a 2  s.  co  m*/
private StoryFragment createStoryFragment(Cursor cursor) {
    UUID storyID, fragmentID;
    String storyText;
    ArrayList<Choice> choices;
    ArrayList<Image> images;
    ArrayList<UUID> uuids;
    storyID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_STORYID)));
    fragmentID = UUID.fromString(cursor.getString(cursor.getColumnIndex(StoryDB.COLUMN_GUID)));
    storyText = cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_CONTENT));
    String json = cursor.getString(cursor.getColumnIndex(StoryDB.STORYFRAGMENT_COLUMN_CHOICES));
    Gson gson = new Gson();
    Type collectionType = new TypeToken<Collection<Choice>>() {
    }.getType();
    choices = gson.fromJson(json, collectionType);
    json = cursor.getString(cursor.getColumnIndex(STORYFRAGMENT_COLUMN_IMAGES));
    collectionType = new TypeToken<Collection<UUID>>() {
    }.getType();
    uuids = gson.fromJson(json, collectionType);
    images = getImages(uuids);

    return new StoryFragment(storyID, fragmentID, storyText, images, choices);
}

From source file:ca.cmput301w14t09.FileManaging.FileLoading.java

License:GNU General Public License

/**
 * returnUser loads a specific user and 
 * user data from the device/*  w  w  w . j a  va  2 s  . c om*/
 * @param name
 * @param main
 * @return
 */
public static User returnUser(String name, Activity main) {
    Gson gson = new Gson();
    try {
        FileInputStream fis = main.openFileInput(name + ".sav");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader buff = new BufferedReader(isr);
        String jsonOut = buff.readLine();
        user = gson.fromJson(jsonOut, User.class);
        buff.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return user;
}

From source file:ca.cmput301w14t09.Model.Comment.java

License:GNU General Public License

/**
 * load loads this object, specified by name, from cache with userName.sav
 * @param userName - name of current user (cache is user-based)
 * @param name - name of the file object itself?
 * @param main - activity calling this function.
 * @return - the loaded comment./*from   ww w .j  a v  a  2s.c  o m*/
 */

public Comment load(String userName, String name, Activity main) {
    Gson gson = new Gson();
    Comment comment = null;
    try {
        FileInputStream fis = main.openFileInput(userName + ".sav");
        InputStreamReader isr = new InputStreamReader(fis);
        BufferedReader buff = new BufferedReader(isr);
        String jsonOut = buff.readLine();
        comment = gson.fromJson(jsonOut, Comment.class);
        buff.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return comment;
}