Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "pageInfo": {
- "pageName": "abc",
- "pagePic": "http://example.com/content.jpg"
- }
- "posts": [
- {
- "post_id": "123456789012_123456789012",
- "actor_id": "1234567890",
- "picOfPersonWhoPosted": "http://example.com/photo.jpg",
- "nameOfPersonWhoPosted": "Jane Doe",
- "message": "Sounds cool. Can't wait to see it!",
- "likesCount": "2",
- "comments": [],
- "timeOfPost": "1234567890"
- }
- ]
- }
- import org.json.*;
- JSONObject obj = new JSONObject(" .... ");
- String pageName = obj.getJSONObject("pageInfo").getString("pageName");
- JSONArray arr = obj.getJSONArray("posts");
- for (int i = 0; i < arr.length(); i++)
- {
- String post_id = arr.getJSONObject(i).getString("post_id");
- ......
- }
- private class Person {
- public String name;
- public Person(String name) {
- this.name = name;
- }
- }
- Gson g = new Gson();
- Person person = g.fromJson("{"name": "John"}", Person.class);
- System.out.println(person.name); //John
- System.out.println(g.toJson(person)); // {"name":"John"}
- JsonObject jsonObject = new JsonParser().parse("{"name": "John"}").getAsJsonObject();
- System.out.println(jsonObject.get("name").getAsString()); //John
- JSONObject obj = new JSONObject("{"name": "John"}");
- System.out.println(obj.getString("name")); //John
- ObjectMapper mapper = new ObjectMapper();
- Person user = mapper.readValue("{"name": "John"}", Person.class);
- System.out.println(user.name); //John
- //from object to JSON
- Gson gson = new Gson();
- gson.toJson(yourObject);
- // from JSON to object
- yourObject o = gson.fromJson(JSONString,yourObject.class);
- Response response = request.get(); // REST call
- JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
- JsonArray jsonArray = jsonReader.readArray();
- ListIterator l = jsonArray.listIterator();
- while ( l.hasNext() ) {
- JsonObject j = (JsonObject)l.next();
- JsonObject ciAttr = j.getJsonObject("ciAttributes");
- JsonParserFactory factory=JsonParserFactory.getInstance();
- JSONParser parser=factory.newJsonParser();
- Map jsonMap=parser.parseJson(jsonString);
- <dependency>
- <groupId>com.jayway.jsonpath</groupId>
- <artifactId>json-path</artifactId>
- <version>${version}</version>
- </dependency>
- String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName");
- String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic");
- String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id");
- com.fasterxml.jackson.databind.ObjectMapper
- package com.levo.jsonex.model;
- public class Page {
- private PageInfo pageInfo;
- private Post[] posts;
- public PageInfo getPageInfo() {
- return pageInfo;
- }
- public void setPageInfo(PageInfo pageInfo) {
- this.pageInfo = pageInfo;
- }
- public Post[] getPosts() {
- return posts;
- }
- public void setPosts(Post[] posts) {
- this.posts = posts;
- }
- }
- package com.levo.jsonex.model;
- public class PageInfo {
- private String pageName;
- private String pagePic;
- public String getPageName() {
- return pageName;
- }
- public void setPageName(String pageName) {
- this.pageName = pageName;
- }
- public String getPagePic() {
- return pagePic;
- }
- public void setPagePic(String pagePic) {
- this.pagePic = pagePic;
- }
- }
- package com.levo.jsonex.model;
- public class Post {
- private String post_id;
- private String actor_id;
- private String picOfPersonWhoPosted;
- private String nameOfPersonWhoPosted;
- private String message;
- private int likesCount;
- private String[] comments;
- private int timeOfPost;
- public String getPost_id() {
- return post_id;
- }
- public void setPost_id(String post_id) {
- this.post_id = post_id;
- }
- public String getActor_id() {
- return actor_id;
- }
- public void setActor_id(String actor_id) {
- this.actor_id = actor_id;
- }
- public String getPicOfPersonWhoPosted() {
- return picOfPersonWhoPosted;
- }
- public void setPicOfPersonWhoPosted(String picOfPersonWhoPosted) {
- this.picOfPersonWhoPosted = picOfPersonWhoPosted;
- }
- public String getNameOfPersonWhoPosted() {
- return nameOfPersonWhoPosted;
- }
- public void setNameOfPersonWhoPosted(String nameOfPersonWhoPosted) {
- this.nameOfPersonWhoPosted = nameOfPersonWhoPosted;
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public int getLikesCount() {
- return likesCount;
- }
- public void setLikesCount(int likesCount) {
- this.likesCount = likesCount;
- }
- public String[] getComments() {
- return comments;
- }
- public void setComments(String[] comments) {
- this.comments = comments;
- }
- public int getTimeOfPost() {
- return timeOfPost;
- }
- public void setTimeOfPost(int timeOfPost) {
- this.timeOfPost = timeOfPost;
- }
- }
- {
- "pageInfo": {
- "pageName": "abc",
- "pagePic": "http://example.com/content.jpg"
- },
- "posts": [
- {
- "post_id": "123456789012_123456789012",
- "actor_id": "1234567890",
- "picOfPersonWhoPosted": "http://example.com/photo.jpg",
- "nameOfPersonWhoPosted": "Jane Doe",
- "message": "Sounds cool. Can't wait to see it!",
- "likesCount": "2",
- "comments": [],
- "timeOfPost": "1234567890"
- }
- ]
- }
- package com.levo.jsonex;
- import java.io.File;
- import java.io.IOException;
- import java.util.Arrays;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import com.levo.jsonex.model.Page;
- import com.levo.jsonex.model.PageInfo;
- import com.levo.jsonex.model.Post;
- public class JSONDemo {
- public static void main(String[] args) {
- ObjectMapper objectMapper = new ObjectMapper();
- try {
- Page page = objectMapper.readValue(new File("sampleJSONFile.json"), Page.class);
- printParsedObject(page);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- private static void printParsedObject(Page page) {
- printPageInfo(page.getPageInfo());
- System.out.println();
- printPosts(page.getPosts());
- }
- private static void printPageInfo(PageInfo pageInfo) {
- System.out.println("Page Info;");
- System.out.println("**********");
- System.out.println("tPage Name : " + pageInfo.getPageName());
- System.out.println("tPage Pic : " + pageInfo.getPagePic());
- }
- private static void printPosts(Post[] posts) {
- System.out.println("Page Posts;");
- System.out.println("**********");
- for(Post post : posts) {
- printPost(post);
- }
- }
- private static void printPost(Post post) {
- System.out.println("tPost Id : " + post.getPost_id());
- System.out.println("tActor Id : " + post.getActor_id());
- System.out.println("tPic Of Person Who Posted : " + post.getPicOfPersonWhoPosted());
- System.out.println("tName Of Person Who Posted : " + post.getNameOfPersonWhoPosted());
- System.out.println("tMessage : " + post.getMessage());
- System.out.println("tLikes Count : " + post.getLikesCount());
- System.out.println("tComments : " + Arrays.toString(post.getComments()));
- System.out.println("tTime Of Post : " + post.getTimeOfPost());
- }
- }
- Page Info;
- ****(*****
- Page Name : abc
- Page Pic : http://example.com/content.jpg
- Page Posts;
- **********
- Post Id : 123456789012_123456789012
- Actor Id : 1234567890
- Pic Of Person Who Posted : http://example.com/photo.jpg
- Name Of Person Who Posted : Jane Doe
- Message : Sounds cool. Can't wait to see it!
- Likes Count : 2
- Comments : []
- Time Of Post : 1234567890
- {
- "order": 4711,
- "items": [
- {
- "name": "NE555 Timer IC",
- "cat-id": "645723",
- "quantity": 10,
- },
- {
- "name": "LM358N OpAmp IC",
- "cat-id": "764525",
- "quantity": 2
- }
- ]
- }
- JsonObject object = Json.parse(input).asObject();
- int orders = object.get("order").asInt();
- JsonArray items = object.get("items").asArray();
- JsonObject user = Json.object().add("name", "Sakib").add("age", 23);
- <dependency>
- <groupId>com.eclipsesource.minimal-json</groupId>
- <artifactId>minimal-json</artifactId>
- <version>0.9.4</version>
- </dependency>
- {
- "pageInfo": {
- "pageName": "abc",
- "pagePic": "http://example.com/content.jpg"
- }
- "posts": [
- {
- "post_id": "123456789012_123456789012",
- "actor_id": "1234567890",
- "picOfPersonWhoPosted": "http://example.com/photo.jpg",
- "nameOfPersonWhoPosted": "Jane Doe",
- "message": "Sounds cool. Can't wait to see it!",
- "likesCount": "2",
- "comments": [],
- "timeOfPost": "1234567890"
- }
- ]
- class MyModel {
- private PageInfo pageInfo;
- private ArrayList<Post> posts = new ArrayList<>();
- }
- class PageInfo {
- private String pageName;
- private String pagePic;
- }
- class Post {
- private String post_id;
- @SerializedName("actor_id") // <- example SerializedName
- private String actorId;
- private String picOfPersonWhoPosted;
- private String nameOfPersonWhoPosted;
- private String message;
- private String likesCount;
- private ArrayList<String> comments;
- private String timeOfPost;
- }
- MyModel model = gson.fromJson(jsonString, MyModel.class);
- JSONArray rootOfPage = new JSONArray(JSONString);
- javax.json.JsonReader jr =
- javax.json.Json.createReader(new StringReader(jsonText));
- javax.json.JsonObject jo = jr.readObject();
- //Read the page info.
- javax.json.JsonObject pageInfo = jo.getJsonObject("pageInfo");
- System.out.println(pageInfo.getString("pageName"));
- //Read the posts.
- javax.json.JsonArray posts = jo.getJsonArray("posts");
- //Read the first post.
- javax.json.JsonObject post = posts.getJsonObject(0);
- //Read the post_id field.
- String postId = post.getString("post_id");
- Message message= new ObjectMapper().readValue(jsonString, Message.class);
- {
- "pageInfo": {
- "pageName": "abc",
- "pagePic": "http://example.com/content.jpg"
- }
- "posts": [
- {
- "post_id": "123456789012_123456789012",
- "actor_id": 1234567890,
- "picOfPersonWhoPosted": "http://example.com/photo.jpg",
- "nameOfPersonWhoPosted": "Jane Doe",
- "message": "Sounds cool. Can't wait to see it!",
- "likesCount": 2,
- "comments": [],
- "timeOfPost": 1234567890
- }
- ]
- }
- @Generated("org.jsonschema2pojo")
- public class Container {
- @SerializedName("pageInfo")
- @Expose
- public PageInfo pageInfo;
- @SerializedName("posts")
- @Expose
- public List<Post> posts = new ArrayList<Post>();
- }
- @Generated("org.jsonschema2pojo")
- public class PageInfo {
- @SerializedName("pageName")
- @Expose
- public String pageName;
- @SerializedName("pagePic")
- @Expose
- public String pagePic;
- }
- @Generated("org.jsonschema2pojo")
- public class Post {
- @SerializedName("post_id")
- @Expose
- public String postId;
- @SerializedName("actor_id")
- @Expose
- public long actorId;
- @SerializedName("picOfPersonWhoPosted")
- @Expose
- public String picOfPersonWhoPosted;
- @SerializedName("nameOfPersonWhoPosted")
- @Expose
- public String nameOfPersonWhoPosted;
- @SerializedName("message")
- @Expose
- public String message;
- @SerializedName("likesCount")
- @Expose
- public long likesCount;
- @SerializedName("comments")
- @Expose
- public List<Object> comments = new ArrayList<Object>();
- @SerializedName("timeOfPost")
- @Expose
- public long timeOfPost;
- }
- public class MyObj {
- private PageInfo pageInfo;
- private List<Post> posts;
- static final class PageInfo {
- private String pageName;
- private String pagePic;
- }
- static final class Post {
- private String post_id;
- @JsonProperty("actor_id");
- private String actorId;
- @JsonProperty("picOfPersonWhoPosted")
- private String pictureOfPoster;
- @JsonProperty("nameOfPersonWhoPosted")
- private String nameOfPoster;
- private String likesCount;
- private List<String> comments;
- private String timeOfPost;
- }
- private static final ObjectMapper JACKSON = new ObjectMapper();
- public static void main(String[] args) throws IOException {
- MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
- }
- }
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import com.google.gson.Gson;
- public class GsonExample {
- public static void main(String[] args) {
- Gson gson = new Gson();
- try {
- BufferedReader br = new BufferedReader(
- new FileReader("c:\file.json"));
- //convert the json string back to object
- DataObject obj = gson.fromJson(br, DataObject.class);
- System.out.println(obj);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- JSONParser jsonParser = new JSONParser();
- JSONObject obj = (JSONObject) jsonParser.parse(contentString);
- String product = (String) jsonObject.get("productId");
- {
- "pageInfo": {
- "pageName": "abc",
- "pagePic": "http://example.com/content.jpg"
- },
- "posts": [
- {
- "post_id": "123456789012_123456789012",
- "actor_id": "1234567890",
- "picOfPersonWhoPosted": "http://example.com/photo.jpg",
- "nameOfPersonWhoPosted": "Jane Doe",
- "message": "Sounds cool. Can't wait to see it!",
- "likesCount": "2",
- "comments": [],
- "timeOfPost": "1234567890"
- }
- ]
- }
- Java code :
- JSONObject obj = new JSONObject(responsejsonobj);
- String pageName = obj.getJSONObject("pageInfo").getString("pageName");
- JSONArray arr = obj.getJSONArray("posts");
- for (int i = 0; i < arr.length(); i++)
- {
- String post_id = arr.getJSONObject(i).getString("post_id");
- ......etc
- }
- private static final String EXTRACTOR_SCRIPT =
- "var fun = function(raw) { " +
- "var json = JSON.parse(raw); " +
- "return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";
- public void run() throws ScriptException, NoSuchMethodException {
- ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
- engine.eval(EXTRACTOR_SCRIPT);
- Invocable invocable = (Invocable) engine;
- JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
- result.values().forEach(e -> System.out.println(e));
- }
- var fun = function(raw) {JSON.parse(raw).entries};
- (JSObject) invocable.invokeFunction("fun", json);
- new JSONObject(JSON).getJSONArray("entries");
- mapper.readValue(JSON, Entries.class).getEntries();
- Gson gson = new Gson();
- JsonObject jsonObject = gson.fromJson(jsonAsString, JsonObject.class);
- String pageName = jsonObject.getAsJsonObject("pageInfo").get("pageName").getAsString();
- String pagePic = jsonObject.getAsJsonObject("pageInfo").get("pagePic").getAsString();
- String postId = jsonObject.getAsJsonArray("posts").get(0).getAsJsonObject().get("post_id").getAsString();
- JsonArray posts = jsonObject.getAsJsonArray("posts");
- for (JsonElement post : posts) {
- String postId = post.getAsJsonObject().get("post_id").getAsString();
- //do something
- }
- JSONObject jsonObj = new JSONObject(<jsonStr>);
- String id = jsonObj.getString("pageInfo");
- Employee employee = null;
- ObjectMapper mapper = new ObjectMapper();
- try{
- employee = mapper.readValue(newFile("/home/sumit/employee.json"),Employee.class);
- } catch (JsonGenerationException e){
- e.printStackTrace();
- }
- {
- "data":
- {
- "translations":
- [
- {
- "translatedText": "Arbeit"
- }
- ]
- }
- }
- String json = callToTranslateApi("work", "de");
- JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
- return jsonObject.get("data").getAsJsonObject()
- .get("translations").getAsJsonArray()
- .get(0).getAsJsonObject()
- .get("translatedText").getAsString();
- class ApiResponse {
- Data data;
- class Data {
- Translation[] translations;
- class Translation {
- String translatedText;
- }
- }
- }
- Gson g = new Gson();
- String json =callToTranslateApi("work", "de");
- ApiResponse response = g.fromJson(json, ApiResponse.class);
- return response.data.translations[0].translatedText;
- <dependency>
- <groupId>com.jayway.jsonpath</groupId>
- <artifactId>json-path</artifactId>
- <version>2.2.0</version>
- </dependency>
- BufferedReader br = new BufferedReader(new FileReader("D:\sampleJson.txt"));
- StringBuilder sb = new StringBuilder();
- String line = br.readLine();
- while (line != null) {
- sb.append(line);
- sb.append(System.lineSeparator());
- line = br.readLine();
- }
- br.close();
- String jsonInput = sb.toString();
- Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
- String pageName = JsonPath.read(document, "$.pageInfo.pageName");
- String pagePic = JsonPath.read(document, "$.pageInfo.pagePic");
- String post_id = JsonPath.read(document, "$.posts[0].post_id");
- System.out.println("$.pageInfo.pageName "+pageName);
- System.out.println("$.pageInfo.pagePic "+pagePic);
- System.out.println("$.posts[0].post_id "+post_id);
- $.pageInfo.pageName = abc
- $.pageInfo.pagePic = http://example.com/content.jpg
- $.posts[0].post_id = 123456789012_123456789012
- {
- "pageInfo": {
- "pageName": "abc",
- "pagePic": "http://example.com/content.jpg"
- }
- }
- class PageInfo {
- private String pageName;
- private String pagePic;
- //getters and setters
- }
- PageInfo pageInfo = JsonPath.parse(jsonString).read("$.pageInfo", PageInfo.class);
- <dependency>
- <groupId>com.jayway.jsonpath</groupId>
- <artifactId>json-path</artifactId>
- <version>2.2.0</version>
- </dependency>
- ObjectMapper mapper = new ObjectMapper();
- JsonNode yourObj = mapper.readTree("{"k":"v"}");
- JSONObject jObj = new JSONObject(contents.trim());
- Iterator<?> keys = jObj.keys();
- while( keys.hasNext() ) {
- String key = (String)keys.next();
- if ( jObj.get(key) instanceof JSONObject ) {
- System.out.println(jObj.getString(String key));
- }
- }
- {"OK":[{"tavolo":"1","pizza":"magherita","quantita":"12","note":"nothing"},{"tavolo":"1","pizza":"4formaggi","quantita":"1","note":"nothing"}],"success":1}
- $result = mysql_query(your query);
- if (mysql_num_rows($result) > 0) {
- $response["OK"] = array();
- while ($row = mysql_fetch_array($result)) {
- // temp user array
- $product = array();
- $product["tavolo"] = $row["tavolo"];
- $product["pizza"] = $row["pizza"];
- $product["quantita"] = $row["quantita"];
- $product["note"] = $row["note"];
- // push single product into final response array
- array_push($response["OK"], $product);
- }
- // success
- $response["success"] = 1;
- // echoing JSON response
- echo json_encode($response);
- }
- //your activity..
- final String url_all_products = "yoururl.something";
- // JSON Node names
- final String TAG_SUCCESS = "success";
- //Row is your bean
- ArrayList<Row> productsList;
- // products JSONArray
- JSONArray products = null;
- JSONParser jParser = new JSONParser();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- new LoadAllProducts().execute();
- }
- /**
- * Background Async Task
- * */
- class LoadAllProducts extends AsyncTask<String, String, String> {
- /**
- * Before starting background thread Show Progress Dialog
- * */
- @Override
- protected void onPreExecute() {
- // do something
- }
- protected String doInBackground(String... args) {
- JSONObject json = jParser.makeHttpRequest(url_all_products, "GET");
- try {
- success = json.getInt(TAG_SUCCESS);
- if (success == 1) {
- products = json.getJSONArray("OK");
- productsList = new ArrayList<Row>();
- // looping through All Products
- for (int i = 0; i < products.length(); i++) {
- JSONObject c = products.getJSONObject(i);
- Row r = new Row();
- r.setDescription(c.getString("tavolo"));
- r.setLat(c.getString("pizza"));
- r.setLon(c.getString("quantita"));
- r.setGame_sequence(c.getString("note"));
- productsList.add(r);
- }
- }else {/*do something*/}
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return null;
- }
- /**
- * After completing background task Dismiss the progress dialog
- * **/
- protected void onPostExecute(String file_url) {
- // do something
- }
- }
- }
- }
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.UnsupportedEncodingException;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.json.JSONException;
- import org.json.JSONObject;
- public class JSONParser {
- static InputStream is = null;
- static JSONObject jObj = null;
- static String json = "";
- // constructor
- public JSONParser() {
- }
- // function get json from url
- // by making HTTP POST or GET mehtod
- public JSONObject makeHttpRequest(String url, String method) {
- // Making HTTP request
- try {
- // check for request method
- if("POST".equals(method)){
- // request method is POST
- // defaultHttpClient
- DefaultHttpClient httpClient = new DefaultHttpClient();
- HttpPost httpPost = new HttpPost(url);
- HttpResponse httpResponse = httpClient.execute(httpPost);
- HttpEntity httpEntity = httpResponse.getEntity();
- is = httpEntity.getContent();
- }else if("GET".equals(method)){
- // request method is GET
- DefaultHttpClient httpClient = new DefaultHttpClient();
- HttpGet httpGet = new HttpGet(url);
- HttpResponse httpResponse = httpClient.execute(httpGet);
- HttpEntity httpEntity = httpResponse.getEntity();
- is = httpEntity.getContent();
- }
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- is));
- StringBuilder sb = new StringBuilder();
- String line = null;
- while ((line = reader.readLine()) != null) {
- sb.append(line);
- }
- is.close();
- json = sb.toString();
- } catch (Exception e) {
- e.printStackTrace();
- }
- // try parse the string to a JSON object
- try {
- jObj = new JSONObject(json);
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return jObj;
- }
- }
- @Model(className="RepositoryInfo", properties = {
- @Property(name = "id", type = int.class),
- @Property(name = "name", type = String.class),
- @Property(name = "owner", type = Owner.class),
- @Property(name = "private", type = boolean.class),
- })
- final class RepositoryCntrl {
- @Model(className = "Owner", properties = {
- @Property(name = "login", type = String.class)
- })
- static final class OwnerCntrl {
- }
- }
- List<RepositoryInfo> repositories = new ArrayList<>();
- try (InputStream is = initializeStream(args)) {
- Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
- }
- System.err.println("there is " + repositories.size() + " repositories");
- repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
- System.err.println("repository " + repo.getName() +
- " is owned by " + repo.getOwner().getLogin()
- );
- })
Add Comment
Please, Sign In to add comment