Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Tuesday, August 16, 2016

Java convert Json array to typed List

Java convert Json array to typed List


I have a webservice that sends a typed arraylist which I capture via HttpResponse like so:

// create GET request  HttpGet httpGet = new HttpGet("http://localhost:8084/MinecraftRestServer/webresources/Items");  // execute GET request  HttpResponse response = client.execute(httpGet);  // check response  StatusLine statusLine = response.getStatusLine();  int statusCode = statusLine.getStatusCode();  if (statusCode == 200) { // response OK      // retreive response      List recipesList = new ArrayList();      HttpEntity jsonObj = response.getEntity();              //What's next?  

The array that's being sent from the webservice looks like this:

recipesList.add(new Item(1, 11, "diamond_ingot", "Diamond ingot",                  "0,0,0,0,0,0,0,0,1", "air,diamond_ore"));  recipesList.add(new Item(2, 11, "iron_ingot", "Iron ingot",                  "0,0,0,0,0,0,0,0,1", "air,iron_ore"));  

And comes out in this format:

[{"recipeCategory":11,"recipeImageID":"diamond_ingot","recipeDescription":"Diamond ingot","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,diamond_ore","recipeID":1},{"recipeCategory":11,"recipeImageID":"iron_ingot","recipeDescription":"Iron ingot","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,iron_ore","recipeID":2},{"recipeCategory":11,"recipeImageID":"gold_ingot","recipeDescription":"Gold ingot","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,gold_ore","recipeID":3},{"recipeCategory":11,"recipeImageID":"diamond_ore","recipeDescription":"Diamond ore","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,wooden_pickaxe","recipeID":4},{"recipeCategory":11,"recipeImageID":"iron_ore","recipeDescription":"Iron ore","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,wooden_pickaxe","recipeID":5},{"recipeCategory":11,"recipeImageID":"gold_ore","recipeDescription":"Gold ore","recipeLocations":"0,0,0,0,0,0,0,0,1","usedImages":"air,wooden_pickaxe","recipeID":6},{"recipeCategory":2,"recipeImageID":"diamond_boots","recipeDescription":"Boots (Diamond)","recipeLocations":"0,0,0,1,0,1,1,0,1","usedImages":"air,diamond_ingot","recipeID":7},{"recipeCategory":2,"recipeImageID":"gold_boots","recipeDescription":"Boots (Gold)","recipeLocations":"0,0,0,1,0,1,1,0,1","usedImages":"air,gold_ingot","recipeID":8},{"recipeCategory":2,"recipeImageID":"iron_boots","recipeDescription":"Boots (Iron)","recipeLocations":"0,0,0,1,0,1,1,0,1","usedImages":"air,iron_ingot","recipeID":9},{"recipeCategory":2,"recipeImageID":"diamond_leggings","recipeDescription":"Leggings (Diamond)","recipeLocations":"1,1,1,1,0,1,1,0,1","usedImages":"air,diamond_ingot","recipeID":10},{"recipeCategory":2,"recipeImageID":"gold_leggings","recipeDescription":"Leggings (Gold)","recipeLocations":"1,1,1,1,0,1,1,0,1","usedImages":"air,gold_ingot","recipeID":11},{"recipeCategory":2,"recipeImageID":"iron_leggings","recipeDescription":"Leggings (Iron)","recipeLocations":"1,1,1,1,0,1,1,0,1","usedImages":"air,iron_ingot","recipeID":12},{"recipeCategory":2,"recipeImageID":"diamond_chestplate","recipeDescription":"Chestplate (Diamond)","recipeLocations":"1,0,1,1,1,1,1,1,1","usedImages":"air,diamond_ingot","recipeID":13},{"recipeCategory":2,"recipeImageID":"gold_chestplate","recipeDescription":"Chestplate (Gold)","recipeLocations":"1,0,1,1,1,1,1,1,1","usedImages":"air,gold_ingot","recipeID":14},{"recipeCategory":2,"recipeImageID":"iron_chestplate","recipeDescription":"Chestplate (Iron)","recipeLocations":"1,0,1,1,1,1,1,1,1","usedImages":"air,iron_ingot","recipeID":15},{"recipeCategory":2,"recipeImageID":"diamond_helmet","recipeDescription":"Helmet (Diamond)","recipeLocations":"1,1,1,1,0,1,0,0,0","usedImages":"air,diamond_ingot","recipeID":16},{"recipeCategory":2,"recipeImageID":"gold_helmet","recipeDescription":"Helmet (Gold)","recipeLocations":"1,1,1,1,0,1,0,0,0","usedImages":"air,gold_ingot","recipeID":17},{"recipeCategory":2,"recipeImageID":"iron_helmet","recipeDescription":"Helmet   

My question is, how can I convert this back into an arraylist (ArrayList) There is already an Item class present in the client application.

I've read examples about the Gson library but it seems it's not included anymore when compiling in API 17.

What would be the easiest approach?

Answer by SimonSays for Java convert Json array to typed List


Man, google is your friend! A quick search for "android json" or "android json parse" gives you some nice tutorials like this one or this here.

Answer by noone for Java convert Json array to typed List


You could use Jackson to parse the incoming JSON. (Quick introduction)

If you already have a Class with the appropriate properties, it can be as easy as something like this:

public class Items {      private List items;      // getter+setter  }    ObjectMapper mapper = new ObjectMapper();  Items = mapper.readValue(src, Items.class);  

See this for more information.

Answer by MyMasterPeice for Java convert Json array to typed List


Step 1 : Item obj=new Item;    Step 2: Parse the json formar for example here :    [[Example1][1]    Step 3: while parsing put ur values in obj :    obj.recipeCategory=value1;    Step 4: insret ur obj into arraylist:    arrayList.add(obj);  

Answer by H?i Phan Vn for Java convert Json array to typed List


I think you should using json-simple library to parse string Json to JsonObject and convert to simple data type. Example:

JSONArray arrJson = (JSONArray) parser.parse("String json");  

Get each element JSONObject in JSONArray, then parse it to simple data type:

long recipeCategory = (long) jsonObject.get("recipeCategory");  

Answer by Varun for Java convert Json array to typed List


Download and include GSON jar from here in your project if using Eclipse.

If using Android Studio then open your build.gradle and add the below to your dependencies block. Or again you can choose not to use maven and simply drop the jar in your lib folder.

compile 'com.google.code.gson:gson:2.2.4'  

Next, use GSON to construct a list of items. Make sure you have your Item.java class with same member names as in the JSON response

 List recipesList = new ArrayList();   HttpEntity jsonObj = response.getEntity();   String data = EntityUtils.toString(entity);   Log.d("TAG", data);   Gson gson = new GsonBuilder().create();   recipesList = gson.fromJson(data, new TypeToken>() {}.getType());  

Make sure you handle the exceptions appropriately.

Answer by 4gus71n for Java convert Json array to typed List


You can use Gson like many users said, here is an example of a RESTfull client using Gson:

public class RestRequest {      Gson gson = new Gson();        public  T post(String url, Class clazz,          List parameters) {      // Create a new HttpClient and Post Header      HttpClient httpclient = new DefaultHttpClient();      HttpPost httppost = new HttpPost(url);      try {          // Add your data          httppost.setEntity(new UrlEncodedFormEntity(parameters));          // Execute HTTP Post Request          HttpResponse response = httpclient.execute(httppost);          StringBuilder json = inputStreamToString(response.getEntity()                  .getContent());          T gsonObject = gson.fromJson(json.toString(), clazz);          return gsonObject;      } catch (Exception e) {          e.printStackTrace();      }      return null;      }        // Fast Implementation      private StringBuilder inputStreamToString(InputStream is)          throws IOException {      String line = "";      StringBuilder total = new StringBuilder();        // Wrap a BufferedReader around the InputStream      BufferedReader rd = new BufferedReader(new InputStreamReader(is));        // Read response until the end      while ((line = rd.readLine()) != null) {          total.append(line);      }        // Return full string      return total;      }    }  

The usage will be something like this: new RestRequest("myserver.com/rest/somewebservice", SomeClass.class, Arrays.asList(new BasicValuePair("postParameter", "someParameterValue")));

Where SomeClass.class will be Recipe[].class in your case. Also check this question to properly handle server side errors.


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.