Skip to content

Instantly share code, notes, and snippets.

@JaDogg
Created October 19, 2014 08:36
Show Gist options
  • Select an option

  • Save JaDogg/b0bcfe3585d2120a3f53 to your computer and use it in GitHub Desktop.

Select an option

Save JaDogg/b0bcfe3585d2120a3f53 to your computer and use it in GitHub Desktop.
JSON Split
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