Guest User

Untitled

a guest
Jan 18th, 2018
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 25.01 KB | None | 0 0
  1. {
  2. "pageInfo": {
  3. "pageName": "abc",
  4. "pagePic": "http://example.com/content.jpg"
  5. }
  6. "posts": [
  7. {
  8. "post_id": "123456789012_123456789012",
  9. "actor_id": "1234567890",
  10. "picOfPersonWhoPosted": "http://example.com/photo.jpg",
  11. "nameOfPersonWhoPosted": "Jane Doe",
  12. "message": "Sounds cool. Can't wait to see it!",
  13. "likesCount": "2",
  14. "comments": [],
  15. "timeOfPost": "1234567890"
  16. }
  17. ]
  18. }
  19.  
  20. import org.json.*;
  21.  
  22.  
  23. JSONObject obj = new JSONObject(" .... ");
  24. String pageName = obj.getJSONObject("pageInfo").getString("pageName");
  25.  
  26. JSONArray arr = obj.getJSONArray("posts");
  27. for (int i = 0; i < arr.length(); i++)
  28. {
  29. String post_id = arr.getJSONObject(i).getString("post_id");
  30. ......
  31. }
  32.  
  33. private class Person {
  34. public String name;
  35.  
  36. public Person(String name) {
  37. this.name = name;
  38. }
  39. }
  40.  
  41. Gson g = new Gson();
  42.  
  43. Person person = g.fromJson("{"name": "John"}", Person.class);
  44. System.out.println(person.name); //John
  45.  
  46. System.out.println(g.toJson(person)); // {"name":"John"}
  47.  
  48. JsonObject jsonObject = new JsonParser().parse("{"name": "John"}").getAsJsonObject();
  49.  
  50. System.out.println(jsonObject.get("name").getAsString()); //John
  51.  
  52. JSONObject obj = new JSONObject("{"name": "John"}");
  53.  
  54. System.out.println(obj.getString("name")); //John
  55.  
  56. ObjectMapper mapper = new ObjectMapper();
  57. Person user = mapper.readValue("{"name": "John"}", Person.class);
  58.  
  59. System.out.println(user.name); //John
  60.  
  61. //from object to JSON
  62. Gson gson = new Gson();
  63. gson.toJson(yourObject);
  64.  
  65. // from JSON to object
  66. yourObject o = gson.fromJson(JSONString,yourObject.class);
  67.  
  68. Response response = request.get(); // REST call
  69. JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
  70. JsonArray jsonArray = jsonReader.readArray();
  71. ListIterator l = jsonArray.listIterator();
  72. while ( l.hasNext() ) {
  73. JsonObject j = (JsonObject)l.next();
  74. JsonObject ciAttr = j.getJsonObject("ciAttributes");
  75.  
  76. JsonParserFactory factory=JsonParserFactory.getInstance();
  77. JSONParser parser=factory.newJsonParser();
  78. Map jsonMap=parser.parseJson(jsonString);
  79.  
  80. <dependency>
  81. <groupId>com.jayway.jsonpath</groupId>
  82. <artifactId>json-path</artifactId>
  83. <version>${version}</version>
  84. </dependency>
  85.  
  86. String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName");
  87. String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic");
  88. String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id");
  89.  
  90. com.fasterxml.jackson.databind.ObjectMapper
  91.  
  92. package com.levo.jsonex.model;
  93.  
  94. public class Page {
  95.  
  96. private PageInfo pageInfo;
  97. private Post[] posts;
  98.  
  99. public PageInfo getPageInfo() {
  100. return pageInfo;
  101. }
  102.  
  103. public void setPageInfo(PageInfo pageInfo) {
  104. this.pageInfo = pageInfo;
  105. }
  106.  
  107. public Post[] getPosts() {
  108. return posts;
  109. }
  110.  
  111. public void setPosts(Post[] posts) {
  112. this.posts = posts;
  113. }
  114.  
  115. }
  116.  
  117. package com.levo.jsonex.model;
  118.  
  119. public class PageInfo {
  120.  
  121. private String pageName;
  122. private String pagePic;
  123.  
  124. public String getPageName() {
  125. return pageName;
  126. }
  127.  
  128. public void setPageName(String pageName) {
  129. this.pageName = pageName;
  130. }
  131.  
  132. public String getPagePic() {
  133. return pagePic;
  134. }
  135.  
  136. public void setPagePic(String pagePic) {
  137. this.pagePic = pagePic;
  138. }
  139.  
  140. }
  141.  
  142. package com.levo.jsonex.model;
  143.  
  144. public class Post {
  145.  
  146. private String post_id;
  147. private String actor_id;
  148. private String picOfPersonWhoPosted;
  149. private String nameOfPersonWhoPosted;
  150. private String message;
  151. private int likesCount;
  152. private String[] comments;
  153. private int timeOfPost;
  154.  
  155. public String getPost_id() {
  156. return post_id;
  157. }
  158.  
  159. public void setPost_id(String post_id) {
  160. this.post_id = post_id;
  161. }
  162.  
  163. public String getActor_id() {
  164. return actor_id;
  165. }
  166.  
  167. public void setActor_id(String actor_id) {
  168. this.actor_id = actor_id;
  169. }
  170.  
  171. public String getPicOfPersonWhoPosted() {
  172. return picOfPersonWhoPosted;
  173. }
  174.  
  175. public void setPicOfPersonWhoPosted(String picOfPersonWhoPosted) {
  176. this.picOfPersonWhoPosted = picOfPersonWhoPosted;
  177. }
  178.  
  179. public String getNameOfPersonWhoPosted() {
  180. return nameOfPersonWhoPosted;
  181. }
  182.  
  183. public void setNameOfPersonWhoPosted(String nameOfPersonWhoPosted) {
  184. this.nameOfPersonWhoPosted = nameOfPersonWhoPosted;
  185. }
  186.  
  187. public String getMessage() {
  188. return message;
  189. }
  190.  
  191. public void setMessage(String message) {
  192. this.message = message;
  193. }
  194.  
  195. public int getLikesCount() {
  196. return likesCount;
  197. }
  198.  
  199. public void setLikesCount(int likesCount) {
  200. this.likesCount = likesCount;
  201. }
  202.  
  203. public String[] getComments() {
  204. return comments;
  205. }
  206.  
  207. public void setComments(String[] comments) {
  208. this.comments = comments;
  209. }
  210.  
  211. public int getTimeOfPost() {
  212. return timeOfPost;
  213. }
  214.  
  215. public void setTimeOfPost(int timeOfPost) {
  216. this.timeOfPost = timeOfPost;
  217. }
  218.  
  219. }
  220.  
  221. {
  222. "pageInfo": {
  223. "pageName": "abc",
  224. "pagePic": "http://example.com/content.jpg"
  225. },
  226. "posts": [
  227. {
  228. "post_id": "123456789012_123456789012",
  229. "actor_id": "1234567890",
  230. "picOfPersonWhoPosted": "http://example.com/photo.jpg",
  231. "nameOfPersonWhoPosted": "Jane Doe",
  232. "message": "Sounds cool. Can't wait to see it!",
  233. "likesCount": "2",
  234. "comments": [],
  235. "timeOfPost": "1234567890"
  236. }
  237. ]
  238. }
  239.  
  240. package com.levo.jsonex;
  241.  
  242. import java.io.File;
  243. import java.io.IOException;
  244. import java.util.Arrays;
  245.  
  246. import com.fasterxml.jackson.databind.ObjectMapper;
  247. import com.levo.jsonex.model.Page;
  248. import com.levo.jsonex.model.PageInfo;
  249. import com.levo.jsonex.model.Post;
  250.  
  251. public class JSONDemo {
  252.  
  253. public static void main(String[] args) {
  254. ObjectMapper objectMapper = new ObjectMapper();
  255.  
  256. try {
  257. Page page = objectMapper.readValue(new File("sampleJSONFile.json"), Page.class);
  258.  
  259. printParsedObject(page);
  260. } catch (IOException e) {
  261. e.printStackTrace();
  262. }
  263.  
  264. }
  265.  
  266. private static void printParsedObject(Page page) {
  267. printPageInfo(page.getPageInfo());
  268. System.out.println();
  269. printPosts(page.getPosts());
  270. }
  271.  
  272. private static void printPageInfo(PageInfo pageInfo) {
  273. System.out.println("Page Info;");
  274. System.out.println("**********");
  275. System.out.println("tPage Name : " + pageInfo.getPageName());
  276. System.out.println("tPage Pic : " + pageInfo.getPagePic());
  277. }
  278.  
  279. private static void printPosts(Post[] posts) {
  280. System.out.println("Page Posts;");
  281. System.out.println("**********");
  282. for(Post post : posts) {
  283. printPost(post);
  284. }
  285. }
  286.  
  287. private static void printPost(Post post) {
  288. System.out.println("tPost Id : " + post.getPost_id());
  289. System.out.println("tActor Id : " + post.getActor_id());
  290. System.out.println("tPic Of Person Who Posted : " + post.getPicOfPersonWhoPosted());
  291. System.out.println("tName Of Person Who Posted : " + post.getNameOfPersonWhoPosted());
  292. System.out.println("tMessage : " + post.getMessage());
  293. System.out.println("tLikes Count : " + post.getLikesCount());
  294. System.out.println("tComments : " + Arrays.toString(post.getComments()));
  295. System.out.println("tTime Of Post : " + post.getTimeOfPost());
  296. }
  297.  
  298. }
  299.  
  300. Page Info;
  301. ****(*****
  302. Page Name : abc
  303. Page Pic : http://example.com/content.jpg
  304. Page Posts;
  305. **********
  306. Post Id : 123456789012_123456789012
  307. Actor Id : 1234567890
  308. Pic Of Person Who Posted : http://example.com/photo.jpg
  309. Name Of Person Who Posted : Jane Doe
  310. Message : Sounds cool. Can't wait to see it!
  311. Likes Count : 2
  312. Comments : []
  313. Time Of Post : 1234567890
  314.  
  315. {
  316. "order": 4711,
  317. "items": [
  318. {
  319. "name": "NE555 Timer IC",
  320. "cat-id": "645723",
  321. "quantity": 10,
  322. },
  323. {
  324. "name": "LM358N OpAmp IC",
  325. "cat-id": "764525",
  326. "quantity": 2
  327. }
  328. ]
  329. }
  330.  
  331. JsonObject object = Json.parse(input).asObject();
  332. int orders = object.get("order").asInt();
  333. JsonArray items = object.get("items").asArray();
  334.  
  335. JsonObject user = Json.object().add("name", "Sakib").add("age", 23);
  336.  
  337. <dependency>
  338. <groupId>com.eclipsesource.minimal-json</groupId>
  339. <artifactId>minimal-json</artifactId>
  340. <version>0.9.4</version>
  341. </dependency>
  342.  
  343. {
  344. "pageInfo": {
  345. "pageName": "abc",
  346. "pagePic": "http://example.com/content.jpg"
  347. }
  348. "posts": [
  349. {
  350. "post_id": "123456789012_123456789012",
  351. "actor_id": "1234567890",
  352. "picOfPersonWhoPosted": "http://example.com/photo.jpg",
  353. "nameOfPersonWhoPosted": "Jane Doe",
  354. "message": "Sounds cool. Can't wait to see it!",
  355. "likesCount": "2",
  356. "comments": [],
  357. "timeOfPost": "1234567890"
  358. }
  359. ]
  360.  
  361. class MyModel {
  362.  
  363. private PageInfo pageInfo;
  364. private ArrayList<Post> posts = new ArrayList<>();
  365. }
  366.  
  367. class PageInfo {
  368.  
  369. private String pageName;
  370. private String pagePic;
  371. }
  372.  
  373. class Post {
  374.  
  375. private String post_id;
  376.  
  377. @SerializedName("actor_id") // <- example SerializedName
  378. private String actorId;
  379.  
  380. private String picOfPersonWhoPosted;
  381. private String nameOfPersonWhoPosted;
  382. private String message;
  383. private String likesCount;
  384. private ArrayList<String> comments;
  385. private String timeOfPost;
  386. }
  387.  
  388. MyModel model = gson.fromJson(jsonString, MyModel.class);
  389.  
  390. JSONArray rootOfPage = new JSONArray(JSONString);
  391.  
  392. javax.json.JsonReader jr =
  393. javax.json.Json.createReader(new StringReader(jsonText));
  394. javax.json.JsonObject jo = jr.readObject();
  395.  
  396. //Read the page info.
  397. javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
  398. System.out.println(pageInfo.getString("pageName"));
  399.  
  400. //Read the posts.
  401. javax.json.JsonArray posts = jo.getJsonArray("posts");
  402. //Read the first post.
  403. javax.json.JsonObject post = posts.getJsonObject(0);
  404. //Read the post_id field.
  405. String postId = post.getString("post_id");
  406.  
  407. Message message= new ObjectMapper().readValue(jsonString, Message.class);
  408.  
  409. {
  410. "pageInfo": {
  411. "pageName": "abc",
  412. "pagePic": "http://example.com/content.jpg"
  413. }
  414. "posts": [
  415. {
  416. "post_id": "123456789012_123456789012",
  417. "actor_id": 1234567890,
  418. "picOfPersonWhoPosted": "http://example.com/photo.jpg",
  419. "nameOfPersonWhoPosted": "Jane Doe",
  420. "message": "Sounds cool. Can't wait to see it!",
  421. "likesCount": 2,
  422. "comments": [],
  423. "timeOfPost": 1234567890
  424. }
  425. ]
  426. }
  427.  
  428. @Generated("org.jsonschema2pojo")
  429. public class Container {
  430. @SerializedName("pageInfo")
  431. @Expose
  432. public PageInfo pageInfo;
  433. @SerializedName("posts")
  434. @Expose
  435. public List<Post> posts = new ArrayList<Post>();
  436. }
  437.  
  438. @Generated("org.jsonschema2pojo")
  439. public class PageInfo {
  440. @SerializedName("pageName")
  441. @Expose
  442. public String pageName;
  443. @SerializedName("pagePic")
  444. @Expose
  445. public String pagePic;
  446. }
  447.  
  448. @Generated("org.jsonschema2pojo")
  449. public class Post {
  450. @SerializedName("post_id")
  451. @Expose
  452. public String postId;
  453. @SerializedName("actor_id")
  454. @Expose
  455. public long actorId;
  456. @SerializedName("picOfPersonWhoPosted")
  457. @Expose
  458. public String picOfPersonWhoPosted;
  459. @SerializedName("nameOfPersonWhoPosted")
  460. @Expose
  461. public String nameOfPersonWhoPosted;
  462. @SerializedName("message")
  463. @Expose
  464. public String message;
  465. @SerializedName("likesCount")
  466. @Expose
  467. public long likesCount;
  468. @SerializedName("comments")
  469. @Expose
  470. public List<Object> comments = new ArrayList<Object>();
  471. @SerializedName("timeOfPost")
  472. @Expose
  473. public long timeOfPost;
  474. }
  475.  
  476. public class MyObj {
  477.  
  478. private PageInfo pageInfo;
  479. private List<Post> posts;
  480.  
  481. static final class PageInfo {
  482. private String pageName;
  483. private String pagePic;
  484. }
  485.  
  486. static final class Post {
  487. private String post_id;
  488. @JsonProperty("actor_id");
  489. private String actorId;
  490. @JsonProperty("picOfPersonWhoPosted")
  491. private String pictureOfPoster;
  492. @JsonProperty("nameOfPersonWhoPosted")
  493. private String nameOfPoster;
  494. private String likesCount;
  495. private List<String> comments;
  496. private String timeOfPost;
  497. }
  498.  
  499. private static final ObjectMapper JACKSON = new ObjectMapper();
  500. public static void main(String[] args) throws IOException {
  501. MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
  502. }
  503. }
  504.  
  505. import java.io.BufferedReader;
  506. import java.io.FileReader;
  507. import java.io.IOException;
  508. import com.google.gson.Gson;
  509.  
  510. public class GsonExample {
  511. public static void main(String[] args) {
  512.  
  513. Gson gson = new Gson();
  514.  
  515. try {
  516.  
  517. BufferedReader br = new BufferedReader(
  518. new FileReader("c:\file.json"));
  519.  
  520. //convert the json string back to object
  521. DataObject obj = gson.fromJson(br, DataObject.class);
  522.  
  523. System.out.println(obj);
  524.  
  525. } catch (IOException e) {
  526. e.printStackTrace();
  527. }
  528.  
  529. }
  530. }
  531.  
  532. JSONParser jsonParser = new JSONParser();
  533. JSONObject obj = (JSONObject) jsonParser.parse(contentString);
  534. String product = (String) jsonObject.get("productId");
  535.  
  536. {
  537. "pageInfo": {
  538. "pageName": "abc",
  539. "pagePic": "http://example.com/content.jpg"
  540. },
  541. "posts": [
  542. {
  543. "post_id": "123456789012_123456789012",
  544. "actor_id": "1234567890",
  545. "picOfPersonWhoPosted": "http://example.com/photo.jpg",
  546. "nameOfPersonWhoPosted": "Jane Doe",
  547. "message": "Sounds cool. Can't wait to see it!",
  548. "likesCount": "2",
  549. "comments": [],
  550. "timeOfPost": "1234567890"
  551. }
  552. ]
  553. }
  554.  
  555. Java code :
  556.  
  557. JSONObject obj = new JSONObject(responsejsonobj);
  558. String pageName = obj.getJSONObject("pageInfo").getString("pageName");
  559.  
  560. JSONArray arr = obj.getJSONArray("posts");
  561. for (int i = 0; i < arr.length(); i++)
  562. {
  563. String post_id = arr.getJSONObject(i).getString("post_id");
  564. ......etc
  565. }
  566.  
  567. private static final String EXTRACTOR_SCRIPT =
  568. "var fun = function(raw) { " +
  569. "var json = JSON.parse(raw); " +
  570. "return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";
  571.  
  572. public void run() throws ScriptException, NoSuchMethodException {
  573. ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
  574. engine.eval(EXTRACTOR_SCRIPT);
  575. Invocable invocable = (Invocable) engine;
  576. JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
  577. result.values().forEach(e -> System.out.println(e));
  578. }
  579.  
  580. var fun = function(raw) {JSON.parse(raw).entries};
  581.  
  582. (JSObject) invocable.invokeFunction("fun", json);
  583.  
  584. new JSONObject(JSON).getJSONArray("entries");
  585.  
  586. mapper.readValue(JSON, Entries.class).getEntries();
  587.  
  588. Gson gson = new Gson();
  589. JsonObject jsonObject = gson.fromJson(jsonAsString, JsonObject.class);
  590.  
  591. String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
  592. String pagePic = jsonObject.getAsJsonObject("pageInfo").get("pagePic").getAsString();
  593. String postId = jsonObject.getAsJsonArray("posts").get(0).getAsJsonObject().get("post_id").getAsString();
  594.  
  595. JsonArray posts = jsonObject.getAsJsonArray("posts");
  596. for (JsonElement post : posts) {
  597. String postId = post.getAsJsonObject().get("post_id").getAsString();
  598. //do something
  599. }
  600.  
  601. JSONObject jsonObj = new JSONObject(<jsonStr>);
  602.  
  603. String id = jsonObj.getString("pageInfo");
  604.  
  605. Employee employee = null;
  606. ObjectMapper mapper = new ObjectMapper();
  607. try{
  608. employee = mapper.readValue(newFile("/home/sumit/employee.json"),Employee.class);
  609. } catch (JsonGenerationException e){
  610. e.printStackTrace();
  611. }
  612.  
  613. {
  614. "data":
  615. {
  616. "translations":
  617. [
  618. {
  619. "translatedText": "Arbeit"
  620. }
  621. ]
  622. }
  623. }
  624.  
  625. String json = callToTranslateApi("work", "de");
  626. JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
  627. return jsonObject.get("data").getAsJsonObject()
  628. .get("translations").getAsJsonArray()
  629. .get(0).getAsJsonObject()
  630. .get("translatedText").getAsString();
  631.  
  632. class ApiResponse {
  633. Data data;
  634. class Data {
  635. Translation[] translations;
  636. class Translation {
  637. String translatedText;
  638. }
  639. }
  640. }
  641.  
  642. Gson g = new Gson();
  643. String json =callToTranslateApi("work", "de");
  644. ApiResponse response = g.fromJson(json, ApiResponse.class);
  645. return response.data.translations[0].translatedText;
  646.  
  647. <dependency>
  648. <groupId>com.jayway.jsonpath</groupId>
  649. <artifactId>json-path</artifactId>
  650. <version>2.2.0</version>
  651. </dependency>
  652.  
  653. BufferedReader br = new BufferedReader(new FileReader("D:\sampleJson.txt"));
  654.  
  655. StringBuilder sb = new StringBuilder();
  656. String line = br.readLine();
  657.  
  658. while (line != null) {
  659. sb.append(line);
  660. sb.append(System.lineSeparator());
  661. line = br.readLine();
  662. }
  663. br.close();
  664. String jsonInput = sb.toString();
  665.  
  666. Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
  667.  
  668. String pageName = JsonPath.read(document, "$.pageInfo.pageName");
  669. String pagePic = JsonPath.read(document, "$.pageInfo.pagePic");
  670. String post_id = JsonPath.read(document, "$.posts[0].post_id");
  671.  
  672. System.out.println("$.pageInfo.pageName "+pageName);
  673. System.out.println("$.pageInfo.pagePic "+pagePic);
  674. System.out.println("$.posts[0].post_id "+post_id);
  675.  
  676. $.pageInfo.pageName = abc
  677. $.pageInfo.pagePic = http://example.com/content.jpg
  678. $.posts[0].post_id = 123456789012_123456789012
  679.  
  680. {
  681. "pageInfo": {
  682. "pageName": "abc",
  683. "pagePic": "http://example.com/content.jpg"
  684. }
  685. }
  686.  
  687. class PageInfo {
  688.  
  689. private String pageName;
  690. private String pagePic;
  691.  
  692. //getters and setters
  693. }
  694.  
  695. PageInfo pageInfo = JsonPath.parse(jsonString).read("$.pageInfo", PageInfo.class);
  696.  
  697. <dependency>
  698. <groupId>com.jayway.jsonpath</groupId>
  699. <artifactId>json-path</artifactId>
  700. <version>2.2.0</version>
  701. </dependency>
  702.  
  703. ObjectMapper mapper = new ObjectMapper();
  704. JsonNode yourObj = mapper.readTree("{"k":"v"}");
  705.  
  706. JSONObject jObj = new JSONObject(contents.trim());
  707. Iterator<?> keys = jObj.keys();
  708.  
  709. while( keys.hasNext() ) {
  710. String key = (String)keys.next();
  711. if ( jObj.get(key) instanceof JSONObject ) {
  712. System.out.println(jObj.getString(String key));
  713. }
  714. }
  715.  
  716. {"OK":[{"tavolo":"1","pizza":"magherita","quantita":"12","note":"nothing"},{"tavolo":"1","pizza":"4formaggi","quantita":"1","note":"nothing"}],"success":1}
  717.  
  718. $result = mysql_query(your query);
  719. if (mysql_num_rows($result) > 0) {
  720.  
  721. $response["OK"] = array();
  722.  
  723. while ($row = mysql_fetch_array($result)) {
  724. // temp user array
  725. $product = array();
  726. $product["tavolo"] = $row["tavolo"];
  727. $product["pizza"] = $row["pizza"];
  728. $product["quantita"] = $row["quantita"];
  729. $product["note"] = $row["note"];
  730. // push single product into final response array
  731. array_push($response["OK"], $product);
  732. }
  733. // success
  734. $response["success"] = 1;
  735. // echoing JSON response
  736. echo json_encode($response);
  737. }
  738.  
  739. //your activity..
  740.  
  741. final String url_all_products = "yoururl.something";
  742. // JSON Node names
  743. final String TAG_SUCCESS = "success";
  744. //Row is your bean
  745. ArrayList<Row> productsList;
  746. // products JSONArray
  747. JSONArray products = null;
  748. JSONParser jParser = new JSONParser();
  749.  
  750.  
  751. @Override
  752. protected void onCreate(Bundle savedInstanceState) {
  753. super.onCreate(savedInstanceState);
  754.  
  755. new LoadAllProducts().execute();
  756. }
  757.  
  758. /**
  759. * Background Async Task
  760. * */
  761. class LoadAllProducts extends AsyncTask<String, String, String> {
  762.  
  763. /**
  764. * Before starting background thread Show Progress Dialog
  765. * */
  766. @Override
  767. protected void onPreExecute() {
  768. // do something
  769. }
  770.  
  771. protected String doInBackground(String... args) {
  772.  
  773. JSONObject json = jParser.makeHttpRequest(url_all_products, "GET");
  774.  
  775. try {
  776.  
  777. success = json.getInt(TAG_SUCCESS);
  778.  
  779. if (success == 1) {
  780.  
  781. products = json.getJSONArray("OK");
  782.  
  783. productsList = new ArrayList<Row>();
  784.  
  785. // looping through All Products
  786. for (int i = 0; i < products.length(); i++) {
  787. JSONObject c = products.getJSONObject(i);
  788.  
  789. Row r = new Row();
  790. r.setDescription(c.getString("tavolo"));
  791. r.setLat(c.getString("pizza"));
  792. r.setLon(c.getString("quantita"));
  793. r.setGame_sequence(c.getString("note"));
  794.  
  795. productsList.add(r);
  796. }
  797. }else {/*do something*/}
  798. } catch (Exception e) {
  799. // TODO Auto-generated catch block
  800. e.printStackTrace();
  801. }
  802. return null;
  803. }
  804. /**
  805. * After completing background task Dismiss the progress dialog
  806. * **/
  807. protected void onPostExecute(String file_url) {
  808. // do something
  809.  
  810. }
  811. }
  812. }
  813. }
  814.  
  815. import java.io.BufferedReader;
  816. import java.io.IOException;
  817. import java.io.InputStream;
  818. import java.io.InputStreamReader;
  819. import java.io.UnsupportedEncodingException;
  820. import org.apache.http.HttpEntity;
  821. import org.apache.http.HttpResponse;
  822. import org.apache.http.client.ClientProtocolException;
  823. import org.apache.http.client.methods.HttpGet;
  824. import org.apache.http.client.methods.HttpPost;
  825. import org.apache.http.impl.client.DefaultHttpClient;
  826. import org.json.JSONException;
  827. import org.json.JSONObject;
  828. public class JSONParser {
  829. static InputStream is = null;
  830. static JSONObject jObj = null;
  831. static String json = "";
  832. // constructor
  833. public JSONParser() {
  834. }
  835. // function get json from url
  836. // by making HTTP POST or GET mehtod
  837. public JSONObject makeHttpRequest(String url, String method) {
  838. // Making HTTP request
  839. try {
  840. // check for request method
  841. if("POST".equals(method)){
  842. // request method is POST
  843. // defaultHttpClient
  844. DefaultHttpClient httpClient = new DefaultHttpClient();
  845. HttpPost httpPost = new HttpPost(url);
  846. HttpResponse httpResponse = httpClient.execute(httpPost);
  847. HttpEntity httpEntity = httpResponse.getEntity();
  848. is = httpEntity.getContent();
  849. }else if("GET".equals(method)){
  850. // request method is GET
  851. DefaultHttpClient httpClient = new DefaultHttpClient();
  852. HttpGet httpGet = new HttpGet(url);
  853. HttpResponse httpResponse = httpClient.execute(httpGet);
  854. HttpEntity httpEntity = httpResponse.getEntity();
  855. is = httpEntity.getContent();
  856. }
  857. } catch (UnsupportedEncodingException e) {
  858. e.printStackTrace();
  859. } catch (ClientProtocolException e) {
  860. e.printStackTrace();
  861. } catch (IOException e) {
  862. e.printStackTrace();
  863. }
  864. try {
  865. BufferedReader reader = new BufferedReader(new InputStreamReader(
  866. is));
  867. StringBuilder sb = new StringBuilder();
  868. String line = null;
  869. while ((line = reader.readLine()) != null) {
  870. sb.append(line);
  871. }
  872. is.close();
  873. json = sb.toString();
  874. } catch (Exception e) {
  875. e.printStackTrace();
  876. }
  877. // try parse the string to a JSON object
  878. try {
  879. jObj = new JSONObject(json);
  880. } catch (JSONException e) {
  881. e.printStackTrace();
  882. }
  883. return jObj;
  884. }
  885. }
  886.  
  887. @Model(className="RepositoryInfo", properties = {
  888. @Property(name = "id", type = int.class),
  889. @Property(name = "name", type = String.class),
  890. @Property(name = "owner", type = Owner.class),
  891. @Property(name = "private", type = boolean.class),
  892. })
  893. final class RepositoryCntrl {
  894. @Model(className = "Owner", properties = {
  895. @Property(name = "login", type = String.class)
  896. })
  897. static final class OwnerCntrl {
  898. }
  899. }
  900.  
  901. List<RepositoryInfo> repositories = new ArrayList<>();
  902. try (InputStream is = initializeStream(args)) {
  903. Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
  904. }
  905.  
  906. System.err.println("there is " + repositories.size() + " repositories");
  907. repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
  908. System.err.println("repository " + repo.getName() +
  909. " is owned by " + repo.getOwner().getLogin()
  910. );
  911. })
Add Comment
Please, Sign In to add comment