background preloader

Gson User Guide - gson

Gson User Guide - gson
Serializing and Deserializing Collection with Objects of Arbitrary Types Sometimes you are dealing with JSON array that contains mixed types. For example: The equivalent Collection containing this is: Collection collection = new ArrayList(); collection.add("hello"); collection.add(5); collection.add(new Event("GREETINGS", "guest")); Where the Event class is defined as: class Event { private String name; private String source; private Event(String name, String source) { this.name = name; this.source = source; You can serialize the collection with Gson without doing anything specific: toJson(collection) would write out the desired output. However, deserialization with fromJson(json, Collection.class) will not work since Gson has no way of knowing how to map the input to the types. Option 1: Use Gson's parser API (low-level streaming parser or the DOM parser JsonParser) to parse the array elements and then use Gson.fromJson() on each of the array elements.This is the preferred approach. Compact Vs. Related:  fllw

Free ArchiCAD Tutorials - Interactive Training Guides for Self Learning Commentary: Why the new Mac Pro will rock for ArchiCAD but not for Revit by Anthony Frausto-Robledo AIA, LEED AP | Architosh “Multiprocessing support is critical for the BIM database heavy processing, which involves model generation,” says Pfemeter. “And the 12 cores of the Mac Pro will also be utilized for ArchiCAD’s brand new background processing support for both data caching and populating model changes across the BIM.”Read more... Graphisoft has updated its flagship BIM modelling tool, ArchiCAD, with a host of ‘themed’ new features and enhancements. BIM lives in the details. by AECMagazine "Every Building Information Modelling (BIM) vendor claims to be ‘BIM’, but they usually come from a 2D document-centric world and offer a far less integrated solution than the latest ArchiCAD offering. ArchiCAD 17 Goes Deep With Intelligent Building Materials by CAD Insider "ArchiCAD has been in the forefront of architecture software for some time. Product In-Depth: Looking at Graphisoft ArchiCAD 17

GSON Serialiser Example | Java Creed Java objects can be converted into JSON strings using the Gson API (Homepage). In this article we will see how we can convert Java objects into JSON strings using both the default Gson implementation and custom implementation. The readers of this article are encouraged to read the articles: Simple Gson Example and Gson Deserialiser Example, if they are not familiar with Gson. Furthermore, this article is structured in the same way as the article Gson Deserialiser Example and the same examples are used here. Observation Please note the we will use the terms format or serialise interchangeably in this article. All code listed below is available at: Serialiser Example/. Simple Example Consider the following Java object. package com.javacreed.examples.gson.part1; public class Book { private String[] authors; private String isbn10; private String isbn13; private String title; } This is a simple Java class representing a book. Nested Objects

romannurik/Android-WizardPager OkHttp Overview HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is an HTTP client that’s efficient by default: HTTP/2 support allows all requests to the same host to share a socket. OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. Using OkHttp is easy. OkHttp supports Android 2.3 and above. Examples Get a URL This program downloads a URL and print its contents as a string. OkHttpClient client = new OkHttpClient(); String run(String url) throws IOException { Request request = new Request.Builder() .url(url) .build(); Response response = client.newCall(request).execute(); return response.body().string();} Post to a Server This program posts data to a service. Download ↓ v3.4.1 JAR You'll also need Okio, which OkHttp uses for fast I/O and resizable buffers. Maven Gradle compile 'com.squareup.okhttp3:okhttp:3.4.1' Contributing License

Gson & Deserialization of Objects Containing Arrays After my practicum team and I banged our collective heads against the wall for several hours trying to force Gson to deserialize json arrays into a collection of complex classes containing their own collections, we chose to go another route entirely. Our problem at the time was that we had blinders on and couldn’t walk away from using Javas Collections library. I came to realize today that Gson does a fantastic job of deseralizing classes with any depth of arrays so long as those json arrays are actually represented as primitive arrays in your java class. For example: let’s say you had the following json: My previous attempts to deserialize this object might have been to create the following class: And deserialize using the following code (per the user guide): We tried a good deal of tricks to get this to work but never had any real luck with it. Deserialization with: This is so much simpler.

Rest interaction in Android In last December ('13) I was asked to submit a talk proposal for the first Italian Droidcon, which I did. It got accepted, so in Febraury I gave my first public speech speaking of "(O)Authenticated Rest Interaction in Android" in front of real people. This post is meant to be a follow up with the information that can't be found in the slides I hoped to sum all the talk up in a post, but it got too long so I am going to split it in several pieces. This one will cover the asynchronous interaction with a remote webservice. Disclaimer: I am not inventing anything new here, most of the content can be found on the internet. Rule #1: decouple the interaction with the web service from UI components (activities / fragment) There are several reasons for that. You should start thinking that any network operation has a cost, in terms of bandwith and cpu power. Said that, you should (must?) Well, guess what? So where am I supposed to perform the calls? The answer is pretty simple. IntentService! Cool!

Android : Volley and Gson tutorial Android Volley is the new way to make network requests. It has a lot of advantages : configurable thread pool, request priority, caching, request cancel. AsyncTask is no more needed and this is a good new as AsyncTask is known for its memory leak issues. In this quick step tutorial, i show the piece of source code to make it work with google gson library. Test before If you wish to test before, you can install the application with the following link. Your app ideaMichenuxFree Prerequisite At this time, there is no release of volley library so you have to download the source code and copy it inside your project. git clone In the activity Declare a new attribute of type RequestQueue : private RequestQueue requestQueue; In the onCreate method, initialize the RequestCode and let’s call our startRequest method : this.requestQueue = Volley.newRequestQueue(this.getActivity()); startRequest() This is my startRequest method.

Android JSON Parsing example JSON is built on two structures:A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.These are universal data structures. Virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.In JSON, they take on these forms:An object is an unordered set of name/value pairs. An array is an ordered collection of values. A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A number is very much like a C or Java number, except that the octal and hexadecimal formats are not used. // constructor <!

What is Context in Android - SimpleCodeStuffs|SimpleCodeStuffs Context is context of current state of the application/object.It€™s an entity that represents various environment data . Context helps the current activity to interact with out side android environment like local files, databases, class loaders associated to the environment, services including system-level services, and more. A Context is a handle to the system . It provides services like resolving resources, obtaining access to databases and preferences, and so on. An android app has activities. It’s like a handle to the environment your application is currently running in. It lets newly created objects understand what has been going on. According to Android Documentation Interface to global information about an application environment. Different invoking methods by which you can get context 1. getApplicationContext(), 2. getContext(), 3. getBaseContext() 4. or this (when in the activity class). Examples for uses of context: 1. 2. 3. getApplicationContext().getContentResolver().query(uri,

Saving (and Retrieving) Android Instance State - Part 1 - Intertech Blog Why do we need to save instance state? Android activities have a lifecycle (for a diagram of this lifecycle see here). As an activity becomes partially hidden (paused) or fully hidden (stopped), possibly even destroyed, your applications need a way to keep valuable state (i.e. data) the activity has obtained (probably from user input) or created even after the activity has gone away. As an example, an orientation change can cause your activity to be destroyed and removed from memory and then recreated again. Unless you avail yourself to certain state saving mechanisms, any data your activity has at the time of orientation change can be completely lost in this seemingly simple act. How do we save activity instance state? The Activity class provides the first, and possibly easiest, means of saving and restoring activity state. The onSaveInstanceState( ) method is passed a Bundle object as a parameter. Saving State using onSaveInstanceState( ) Example // ... the rest of the activity @Override

Get Started With JSON JSON is a format for describing data that is easily converted to most programming languages. Many APIs, such as Flickr and Twitter, now offer their results in this format. The acronym JSON (pronounced like the name “Jason”) stands for JavaScript Object Notation. It’s a way of annotating data that’s relatively easy for humans to read and write. This helps explain its recent popularity. As Ajax applications, which depend heavily on JavaScript, have become common, programmers have searched for an easy way to transfer data. A Simple Example: A List of Movies Let’s say we wanted to store the first five Friday the 13th movies (Jason? JSON includes a way to describe arrays. The squiggly brackets surround the entire object. Our object has one attribute, named “movielist.” The square brackets contain an array, which holds our ordered list of other values. Creating the JavaScript Object Written directly into JavaScript, our JSON text looks a little different: Accessing the JavaScript Object

Consume Webservice in Android using intentService | Surviving w/ Android Topics covered Consume Webservice in Android IntentService ResultReceiver In this post, I will explain how to consume Restful Webservice using IntentService. We know we can consume a Webservice directly in the UI using for example Volley lib or a simple Http client, but there are some cases when we prefer to consume a Webservice in an Android Service. IntentService description When we want to consume a Webservice, we have to be aware that the time required to contact the server and get the response can be quite long. Creating the IntentService As example we will use Yahoo! The first step is creating a service: At line 4, in onHandleIntent we do the “heavy work”, so we call the remote Webservice and parse the response. Then we define our service in the Manifest.xml: Activity: Webservice client The next step is creating the client activity that invokes the service. At line 18 and 25, we implement the two methods required to marshal and unmarshal our class. This class is very simple.

Retrofit Introduction Retrofit turns your REST API into a Java interface. public interface GitHubService { @GET("/users/{user}/repos") List<Repo> listRepos(@Path("user") String user);} The RestAdapter class generates an implementation of the GitHubService interface. RestAdapter restAdapter = new RestAdapter.Builder() .setEndpoint(" .build(); GitHubService service = restAdapter.create(GitHubService.class); Each call on the generated GitHubService makes an HTTP request to the remote webserver. List<Repo> repos = service.listRepos("octocat"); Use annotations to describe the HTTP request: URL parameter replacement and query parameter support Object conversion to request body (e.g., JSON, protocol buffers) Multipart request body and file upload API Declaration Annotations on the interface methods and its parameters indicate how a request will be handled. Request Method Every method must have an HTTP annotation that provides the request method and relative URL. @GET("/users/list") Download

APIs that Return JSON

Related: