I'm having a Json file like this {"Name":"Saaa","AppIcon":"ddd.jpg","Wallpaper.jpg","ddd.jpg"]}. I need to extract the AppIcon values.I'm using json simple lib to parse the json.The code snippet to parse the values is as below.
FileReader appIconReader = new FileReader("jsonpath.json");
JSONObject jsonIconObject = (JSONObject)jsonParser.parse(appIconReader);
System.out.println("APPLICATION ICON = "+jsonIconObject.get("AppIcon"));
But the output what I'm gettin is a single string as below:
["ddd.jpg","Wallpaper.jpg","ddd.jpg"]
I need to extract the individual values like this
ddd.jpg
Wallpaper.jpg
ddd.jpg
Not with the square brackets([]) and double quotes("") as I'm getting right now.How can I do that?
Try with JSON.
String str="[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
Type collectionType = new TypeToken<String[]>() {
}.getType();
String[] a=new Gson().fromJson(str,collectionType);
for (String i:a){
System.out.println(i);
}
Output
ddd.jpg
Wallpaper.jpg
ddd.jpg
Edit: for your edited question answer like this.
public class Obj{
private String name;
private List<String> appIcons;
public List<String> getAppIcons() {
return appIcons;
}
public void setAppIcons(List<String> appIcons) {
this.appIcons = appIcons;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now you can simply pass your JSON
String str = "{\"name\":\"Saaa\",\"appIcons\":
[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
Obj obj = new Gson().fromJson(str, Obj.class);
System.out.println(obj.getAppIcons());
Output:
[ddd.jpg, Wallpaper.jpg, ddd.jpg]
Assuming you have your source string:
String str = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
Substring it:
str = str.substring(1, str.length() - 1);
Split it:
String[] parts = str.split(",");
Substring each part:
for(int i = 0; i < parts.length; i++) {
parts[i] = parts[i].substring(1, parts[i].length() - 1);
}
Now you have an array with each value. Note that this is unsafe, add checks before substringing.
this is what you want :
String filePath = "pathofjson\\test.json";
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
JSONArray lang= (JSONArray) jsonObject.get("AppIcon");
System.out.println(lang);
for(int i=0; i<lang.size(); i++){
System.out.println(lang.get(i));
}
} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
You can use replaceAll and split
String s="[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
String array[]=s.replaceAll("[\\[\\]\"]", "").split(","));
System.out.println(Arrays.toString(array);
replaceAll removes [ ] and " from String
split gives array of String by splitting the String with use of ,(delimeter)
Arrays.toString used to print Array.
OUTPUT
[ddd.jpg, Wallpaper.jpg, ddd.jpg]
With JSON you can try this
String s="{\"Name\":\"Saaa\","+
" \"AppIcon\":[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
org.json.JSONObject json=new org.json.JSONObject(s);
org.json.JSONArray jarray=json.getJSONArray("AppIcon");
System.out.println(jarray.get(0));//Will give ddd.jpg
//Iterate over array to get all
Try this :
String str = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
String tempStr = str.replaceAll("\\W{2,}", ",");
String substring = tempStr.substring(1, tempStr.length() -1);
String[] strArray = substring.split(",");
You should use java.util.StringTokenizer
String s = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]";
StringTokenizer tokenizer = new StringTokenizer(s, "[\",]");
while (tokenizer.hasMoreElements()) {
System.out.println(tokenizer.nextElement());
}
Here you have a possible solution:
String data = "{\"Name\":\"Saaa\",\"AppIcon\":[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"]}";
data = data.replaceAll("(.*\"AppIcon\":\\[)(.+)(\\].*)", "$2");
data = data.replaceAll("\"", "");
for(String str: data.split(",")) {
System.out.println(str);
}
which only involves the String class explicitly, and works for every String which the format defined in the question (which has "AppIcon:[]").
Following the description this is what you asked for:
String s = "[\"ddd.jpg\",\"Wallpaper.jpg\",\"ddd.jpg\"," +
"\"Wallpaper.jpg\",\"ddd.jpg\"," +
"\"Wallpaper.jpg\",\"ddd.jpg\"]";
String [] almost_the_words = s.split("\",\"");
int l = almost_the_words.length;
ArrayList<String> words = new ArrayList<String>();
String temp1 = almost_the_words[0].split("\"")[1];
String temp2 = almost_the_words[l-1].split("\"")[0];
words.add(temp1);
for(int i=1; i< l-1; i++) {
words.add(almost_the_words[i]);
}
words.add(temp2);
for(String w : words) {
System.out.println(w);
}
EDIT:
Parse a JSON File with those Strings using GSON:
import java.util.ArrayList;
public class MyObject {
ArrayList<String> appicon;
public MyObject(ArrayList<String> appicon) {
super();
this.appicon = appicon;
}
public ArrayList<String> getAppicon() {
return appicon;
}
public void setAppicon(ArrayList<String> appicon) {
this.appicon = appicon;
}
}
Use the class "MyObject" with the Library GSON: https://code.google.com/p/google-gson/
Related
I am facing a problem in reading data from the text file line by line storing it in an arraylist. I have to read the data from arraylist[0] and I have to perform split operation on that data and I have to store the data in a different array.
public class StatsOnData {
public static void main(String args[]) throws IOException {
String gender;
BufferedReader in = new BufferedReader(new FileReader("file path"));
String str;
List<String> list = new ArrayList<String>();`enter code here`
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
System.out.println(list.size());
//spliting the array into a sub array
StringBuilder temp = new StringBuilder();
for(int i=1; i <= list.size(); i++){
for( int j = 0; j < list[i]; j++){
String line = null;
while ((line = .readLine()) != null) {
String[] values = line.split("|");
for (String str1 : values) {
System.out.println(str);
}
}
}
I did not understand your problem but may be you want to do something like this -
BufferedReader in = new BufferedReader(new FileReader("file path"));
String str;
int countMale=0;
int countFemale=0;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
for(String s:list){
String[] splitValues=s.split("|");
for(int i=0;i<splitValues.length;i++){
if(splitValues[i].equalsIgnoreCase("m")){
countMale++;
}
else if(splitValues[i].equalsIgnoreCase("f")){
countFemale++;
}
}
}
System.out.println("Number of males: "+countMale);
System.out.println("Number of females: "+countFemale);
Hope this helps !
To print content of each line in split form,
for(int i=1; i <= list.size(); i++)
{
String line = list.get (i) ;
String[] values = line.split("|");
for (String str1 : values)
{
System.out.print(str);
}
}
You can even use map
Map<String,List<String>> genderNameList = new HashMap<String,List<String>>();
for(int i=1; i <= list.size(); i++)
{
String line = list.get (i) ;
String[] values = line.split("|");
//assuming it won't be null
genderNameList.get ( values[1]).add(values[0]);// need tot take care about null
}
If your string goes like peter||Mr|F||23
List<Person> listOfObj = new ArrayList<Person> ();
for(int i=1; i <= list.size(); i++)
{
String line = list.get (i) ;
String[] values = line.split("|");
//assuming it won't be null
Person p = new Person ( values) ;
}
And person can be as following :
Class Person {
private String name;
private String gender;
private int age;
//provide gettter and setter for all such fields.
Person ( String [] values)
{
name = values[0];
gender = values[1];
age = Integer.valuesOf ( values[2]) ;
....
}
}
Here is my Json String. I want To extract Country Name and Country Id of each Object..
please Help Me for the Same
String===
[{"CountryID":1,"CountryIDNew":1,"Name":"India","Shname":"IN","Des":null,"InternationalCode":null,"ISDCode":"091","Active":true,"SoftDelete":false,"CountryDef":null,"DateOfEntry":"/Date(1380515350000)/","LatestModified":false,"FYID":44,"PeriodId":6,"UserId":107},{"CountryID":2,"CountryIDNew":1,"Name":"India","Shname":"IN","Des":null,"InternationalCode":null,"ISDCode":"091","Active":true,"SoftDelete":false,"CountryDef":null,"DateOfEntry":"/Date(1387793898000)/","LatestModified":true,"FYID":44,"PeriodId":9,"UserId":117}]
Thanks In Advance...
Try this android code.
JsonArray resultJson = new JSONArray(json_string);
for(int i=0;i<resultJson.length();i++)
{
JsonObject jobj = (JSONObject) resultJson.get(i);
String country_id = jobj.getString("CountryID");
String country_name = jobj.getString("Name");
}
You can use this:
Create a class
public class Country{ public String name =""; public String countryId =""; }
And create a array list
ArrayList countryList = new ArrayList();
String serverRes = "[{"CountryID":1,"CountryIDNew":1,"Name":"India","Shname":"IN","Des":null,"InternationalCode":null,"ISDCode":"091","Active":true,"SoftDelete":false,"CountryDef":null,"DateOfEntry":"/Date(1380515350000)/","LatestModified":false,"FYID":44,"PeriodId":6,"UserId":107},{"CountryID":2,"CountryIDNew":1,"Name":"India","Shname":"IN","Des":null,"InternationalCode":null,"ISDCode":"091","Active":true,"SoftDelete":false,"CountryDef":null,"DateOfEntry":"/Date(1387793898000)/","LatestModified":true,"FYID":44,"PeriodId":9,"UserId":117}]";
JSONArray response = new JSONArray(serverRes);
for(int i=0;i<response.length();i++)
{
JSONObject jobj = response.getJSONObject(i);
Country c = new Country();
c.name = jobj.getString("CountryID");
c.countryId = jobj.getString("Name");
countryList.add(c);
}
And you can get array list with data.
use this code
JsonArray resultJson = new JSONArray(json_string);
for(int i=0;i<resultJson.length();i++)
{
JsonObject jobj = resultJson.getJSONObject(i);
if( jobj.has("CountryID") )
{
String country_id = jobj.getString("CountryID");
}
if( jobj.has("Name") )
{
String country_name = jobj.getString("Name");
}
}
hope this help you
This is a small snippet of my code.It works fine but what if I wanted to add a number to each String variable str.
How do I do that?Please help.
Collections.shuffle(arrlist);
for(int i=0;i<nb;i++){
String str = (String) arrlist.get(i);
//worker.parseXHtml(writer, document, new StringReader("<br>"));
worker.parseXHtml(writer, document, new StringReader(str));
}
Try
String str = (String) arrlist.get(i)+String.valueOf(someNumber);
If you want to add i
String str = (String) arrlist.get(i)+String.valueOf(i);
Update
public static void main(String[] args) {
List arrlist = new ArrayList<>();
arrlist.add("tester");
int i = 0;
String str = (String) arrlist.get(i) + String.valueOf(i);
System.out.println(str);
}
o/p:
tester0
public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String startPattern1 = START+attrList[0]+">";
String endPattern1 = END+attrList[0]+">";
String startPattern2 = START+attrList[1]+">";
String endPattern2 = END+attrList[1]+">";
String startPattern3 = START+attrList[2]+">";
String endPattern3 = END+attrList[2]+">";
String startPattern4 = START+attrList[3]+">";
String endPattern4 = END+attrList[3]+">";
String startPattern5 = START+attrList[4]+">";
String endPattern5 = END+attrList[4]+">";
String extract1 = new String(buf);
String extract2 = new String(buf);
String extract3 = new String(buf);
String extract4 = new String(buf);
String extract5 = new String(buf);
extract1 = extract1.substring(extract1.indexOf(startPattern1)+startPattern1.length(), extract1.indexOf(endPattern1));
extract2 = extract2.substring(extract2.indexOf(startPattern2)+startPattern2.length(), extract2.indexOf(endPattern2));
extract3 = extract3.substring(extract3.indexOf(startPattern3)+startPattern3.length(), extract3.indexOf(endPattern3));
extract4 = extract4.substring(extract4.indexOf(startPattern4)+startPattern4.length(), extract4.indexOf(endPattern4));
extract5 = extract5.substring(extract5.indexOf(startPattern5)+startPattern5.length(), extract5.indexOf(endPattern5));
String s = ("BLOPABP"+extract1) + ("\nBLOPCALL"+extract2) +("\nBLOPEXP"+extract3) +("\nBLOPHEAD"+extract4)+("\nBLOPMAJ"+extract5);
return s;
}
How would I tidy up the code above into some sort of loop? Basically I have a file that i'm reading and extract the data within the tags and I'm passing the tags into this TagHandler method and returning the extracted data as a string with the tag headers without the "< START >" and "< END TAG"> leaving only the header on the start tag.
Here you go. This should do what you want.
public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String[] blop = {"BLOPABP", "BLOPCALL", "BLOPEXP", "BLOPHEAD", "BLOPMAJ"};
String s = "";
for (int i = 0; i < attrList.length; i++) {
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = buf.substring(buf.indexOf(startPattern)+startPattern.length(), buf.indexOf(endPattern));
s += blop[i]+extract;
if (i < attrList.length-1) {
s += "\n";
}
}
return s;
}
}
Look out for an out of bounds exception, if attrList has more than 5 elements.
You can try something like this, optimize it if you can :
public String handleTag(String buf, String[] attrList) {
StringBuilder temp = new StringBuilder();
final String[] prefix = {"BLOPABP","\nBLOPCALL","\nBLOPEXP",
"\nBLOPHEAD","\nBLOPMAJ"};
for(int i=0;i<attrList.length;i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = new String(buf);
extract = extract.substring(
extract.indexOf(startPattern)+startPattern.length(),
extract.indexOf(endPattern));
temp.append(prefix[i%5]+extract);
}
return temp.toString();
}
This should work. You can replace = new ArrayList<String> with = new ArrayList<>() if you're using java 7.
private final String START = "<START ";
private final String END = "<END ";
List<String> startPatterns = new ArrayList<String>();//can use ArrayList<> instead if java 1.7
List<String> stringExtracts = new ArrayList<String>();
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
startPatterns.add(startPattern);
String endPattern = END+attrList[i]+">";
endPatterns.add(endPattern);
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
stringExtracts.add(extract);
s += tags[i] + extract;
}
return s;
}
This assumes that you need access to the individual startPatterns, endPatterns and stringExtracts again, not just s. If you only need s though then discard the ArrayLists - it will work like this:
private final String START = "<START ";
private final String END = "<END ";
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
s += tags[i] + extract;
}
return s;
}
For example: { "primary:title":"Little Red Riding Hood"}
My Parser in Java (Android) is always getting stuck because of the colon between primary and title. I can parse anything else with ease, I just need help in this.
public class MainActivity extends Activity {
/** Called when the activity is first created. */
TextView txtViewParsedValue;
private JSONObject jsonObject;
private JSONArray jsonArray;
String [] titles, links, mediaDescriptions, mediaCredits, descriptions, dcCreators, pubDates, categories;
String [] permalinks, texts; // guid
String [] rels, hrefs;
String [] urls, media, heights, widths; // media:content
String strParsedValue = "";
private String strJSONValue;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
strJSONValue = readRawTextFile(this, R.raw.jsonextract);
txtViewParsedValue = (TextView) findViewById(R.id.text_view_1);
try {
parseJSON();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void parseJSON() throws JSONException
{
txtViewParsedValue.setText("Parse 1");
jsonObject = new JSONObject(strJSONValue);
jsonArray = jsonObject.getJSONArray("item");
titles = new String[jsonArray.length()];
links = new String[jsonArray.length()];
permalinks = new String[jsonArray.length()];
texts = new String[jsonArray.length()];
mediaDescriptions = new String[jsonArray.length()];
mediaCredits = new String[jsonArray.length()];
descriptions = new String[jsonArray.length()];
dcCreators = new String[jsonArray.length()];
pubDates = new String[jsonArray.length()];
categories = new String[jsonArray.length()];
txtViewParsedValue.setText("Parse 2");
for (int i=0; i<jsonArray.length(); i++)
{
JSONObject object = jsonArray.getJSONObject(i);
titles[i] = object.getString("title");
links[i] = object.getString("link");
JSONObject guidObj = object.getJSONObject("guid");
permalinks[i] = guidObj.getString("isPermaLink");
texts[i] = guidObj.getString("text");
//mediaDescriptions[i] = object.getString("media:description");
//mediaCredits[i] = object.getString("media:credit");
// *** THE PARSER FAILS IF THE COMMENTED LINES ARE IMPLEMENTED BECAUSE
// OF THE : IN BETWEEN THE NAMES ***
descriptions[i] = object.getString("description");
//dcCreators[i] = object.getString("dc:creator");
pubDates[i] = object.getString("pubDate");
categories[i] = object.getString("category");
}
for (int i=0; i<jsonArray.length(); i++)
{
strParsedValue += "\nTitle: " + titles[i];
strParsedValue += "\nLink: " + links[i];
strParsedValue += "\nPermalink: " + permalinks[i];
strParsedValue += "\nText: " + texts[i];
strParsedValue += "\nMedia Description: " + mediaDescriptions[i];
strParsedValue += "\nMedia Credit: " + mediaCredits[i];
strParsedValue += "\nDescription: " + descriptions[i];
strParsedValue += "\nDC Creator: " + dcCreators[i];
strParsedValue += "\nPublication Date: " + pubDates[i];
strParsedValue += "\nCategory: " + categories[i];
strParsedValue += "\n";
}
txtViewParsedValue.setText(strParsedValue);
}
public static String readRawTextFile(Context ctx, int resId)
{
InputStream inputStream = ctx.getResources().openRawResource(resId);
InputStreamReader inputreader = new InputStreamReader(inputStream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
StringBuilder text = new StringBuilder();
try {
while (( line = buffreader.readLine()) != null) {
text.append(line);
//text.append('\n');
}
} catch (IOException e) {
return null;
}
return text.toString();
}
For one, and to answer your question, there is no issue with JSONObject and the org.json.* classes parsing keys with colons in them if they're properly formed. The following unit test passed which means it was able to parse your example scenario:
public void testParsingKeysWithColons() throws JSONException {
String raw = "{ \"primary:title\":\"Little Red Riding Hood\"}";
JSONObject obj = new JSONObject(raw);
String primaryTitle = obj.getString("primary:title");
assertEquals("Little Red Riding Hood", primaryTitle);
}
Another suggestion is that using arrays of Strings for your data is clumsy and you'd be much better organized using a data structure to represent your objects. Instead of string arrays for titles, links, descriptions; use an object that has these properties and make a list of the objects. For example:
public class MyDataStructure {
public String title;
public String primaryTitle;
public String link;
public String mediaDescription;
public static class Keys {
public static String title = "title";
public static String primaryTitle = "primary:title";
public static String link = "link";
public static String mediaDescription = "media:description";
}
}
And then you can make a "translator" class that does all the parsing for you and returns a list of your object. This is much easier to work with and keep track of. You never have to think about data misaligning or having more or less data in one of your arrays than you expected. You also have a much easier time testing where the problem is if your input data is missing anything or any of your json is malformed.
public class MyDataStructureTranslator {
public static List<MyDataStructure> parseJson(String rawJsonData) throws JSONException {
List<MyDataStructure> list = new ArrayList<MyDataStructure>();
JSONObject obj = new JSONObject(rawJsonData);
JSONArray arr = obj.getJSONArray("item");
for(int i = 0; i < arr.length(); i++) {
JSONObject current = arr.getJSONObject(i);
MyDataStructure item = new MyDataStructure();
item.title = current.getString(MyDataStructure.Keys.title);
item.primaryTitle = current.getString(MyDataStructure.Keys.primaryTitle);
item.link = current.getString(MyDataStructure.Keys.link);
item.mediaDescription = current.getString(MyDataStructure.Keys.mediaDescription);
list.add(item);
}
return list;
}
}
Since Java identifiers cannot have colons, just specify a json property name that maps to the exact json name like:
#JsonProperty("primary:title")
public String primaryTitle;