Created
October 19, 2014 08:36
-
-
Save JaDogg/b0bcfe3585d2120a3f53 to your computer and use it in GitHub Desktop.
JSON Split
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package jsonsplit; | |
| import java.util.ArrayList; | |
| import java.util.List; | |
| /** | |
| * JSON Split | |
| * @author Bhathiya | |
| */ | |
| public class JSONSplit { | |
| public static class Food { | |
| private final String id; | |
| private final String name; | |
| public Food(String id, String name) { | |
| this.id = id; | |
| this.name = name; | |
| } | |
| public String getId() { | |
| return id; | |
| } | |
| public String getName() { | |
| return name; | |
| } | |
| @Override | |
| public String toString() { | |
| return "Food{" + "id=" + id + ", name=" + name + '}'; | |
| } | |
| } | |
| public static void main(String[] args) { | |
| final String json | |
| = "str=1,\"name\":\"Rice \"},{\"id\":2,\"name\":\"Milk \"},{\"id\":3,\"name\":\"Suger \"},{\"id\":4,\"name\":\"Dhall \"},{\"id\":5,\"name\":\"Salt \"},{\"id\":6,\"name\":\"Chicken \"},{\"id\":7,\"name\":\"Egg \"}]}"; | |
| String[] splitData = json.split("\\},\\{\\\"id\\\":|,\\\"name\\\":\\\""); | |
| List<Food> foodList = new ArrayList<Food>(); | |
| for (int i = 0; i < splitData.length; i += 2) { | |
| String id = splitData[i].replaceAll("[^0-9]", ""); //remove non numeric characters | |
| String name = splitData[i + 1].replaceAll(" \\\".*", ""); //fix split | |
| //fix split is not needed if the original string's format is same for each food items | |
| foodList.add(new Food(id, name)); | |
| } | |
| for(Food food:foodList){ | |
| System.out.println(food); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment