2

I am trying to parse a json string to java object. Currently the code is manually reading file and generating java object. However, I am looking to take the implementation to gson.

Here is the json that I receive from the web service call:

{ "comment": [
        "This file is used to define the behavior for the elements parsed.",
        "Each entry in the file will have the format of element:name, skip:bool",
        "If SkipFlag is true, it means that element need not be processed.",
        "Convention used for elements and rule names is camelCase"
    ],
    "rules": [ { "element": "html", "skip": true },
               { "element": "head", "skip": true },
               { "element": "head", "skip": true },
               { "element": "body", "skip": true }
    ]
}

I need to ignore the comments and convert rules. Here is the java type I am trying to define for rules java object:

// Arraylist < Map < elementname, Map < name, value >  > >
ArrayList< Map<String, Map<String, String>  > > rules;

Is there an easy way of doing this with gson?

3 Answers 3

5

Use this

GsonBuilder builder = new GsonBuilder();    
Gson gson = builder.enableComplexMapKeySerialization().create(); 
Type type = new TypeToken<ArrayList< Map<String, ArrayList<Map<String, String> > > >>() {}.getType();
ArrayList< Map<String, ArrayList<Map<String, String> > > > obj = gson.fromJson(str, type);
Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain a bit pls? Does the type specification in gson.fromJson automatically look for matching type from the json? I am trying to understand how 'comment' object is skipped.
The type specification (new TypeToken etc.) assist Gson to serialize complex types (i.e. list of objects or even maps when the key derived from object, though in your case your map uses plain String). I guess you can create a custom type suitable your JSON string , de serialize it (including the comments !) and simply ignore them
3

You may declare specific classes:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.Gson;

class Rule {
   String  element;
   boolean skip;
}

class ElementParser {
   String[] comment;
   Rule[]   rules;
}

public class JSonDecoder {
   public static void main( String[] args ) throws IOException {
      try( BufferedReader reader =
              new BufferedReader( new FileReader( "Skip.json" ))) {
         System.out.println( 
            new Gson().fromJson( reader, ElementParser.class ).toString());
      }
   }
}

Here is the long version:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

import com.google.gson.Gson;

class Rule {
   String element;
   boolean skip;

   @Override public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append( '\t' );
      sb.append( element );
      sb.append( " ==> " );
      sb.append( skip );
      sb.append( '\n' );
      return sb.toString();
   }   
}
class ElementParser {
   String[] comment;
   Rule[]    rules;

   @Override public String toString() {
      StringBuilder sb = new StringBuilder();
      sb.append( "Comment:\n" );
      for( String c : comment ) {
         sb.append( '\t' );
         sb.append( c );
         sb.append( '\n' );
      }
      sb.append( "Rules:\n" );
      for( Rule r : rules ) {
         sb.append( r.toString());
      }
      return sb.toString();
   }
}

public class JSonDecoder {
   public static void main( String[] args ) throws IOException {
      try( BufferedReader reader = new BufferedReader( new FileReader( "Skip.json" ))) {
         System.out.println( 
            new Gson().fromJson( reader, ElementParser.class ).toString());
      }
   }
}

Result:

Comment:
    This file is used to define the behavior for the elements parsed.
    Each entry in the file will have the format of element:name, skip:bool
    If SkipFlag is true, it means that element need not be processed.
    Convention used for elements and rule names is camelCase
Rules:
    html ==> true
    head ==> true
    head ==> true
    body ==> true

1 Comment

The rule is 'only one public class per file'. docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.6
1

You can try this too..

A Data class for holding your rules and comments

import java.util.List;

public class Data {

    private List<String> comments;
    private List<Rule> rules;

    public Data() {}

    public List<String> getComments() {
        return comments;
    }

    public void setComments(List<String> comments) {
        this.comments = comments;
    }

    public List<Rule> getRules() {
        return rules;
    }

    public void setRules(List<Rule> rules) {
        this.rules = rules;
    }

}

The Rule class for holding element and skip public class Rule {

    private String element;
    private boolean skip;

    public Rule() {}

    public String getElement() {
        return element;
    }

    public void setElement(String element) {
        this.element = element;
    }

    public boolean isSkip() {
        return skip;
    }

    public void setSkip(boolean skip) {
        this.skip = skip;
    }

}

Finally, you can use something like this for converting rules in your json to java:

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;

import com.google.gson.Gson;

public class GsonTest {

    public static void main(String[] args) throws FileNotFoundException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("C:/Users/JESNAMOL/Desktop/json.txt"));//i have kept  your json string in a file for demonstration
        Gson gson = new Gson();
        Data data = gson.fromJson(bufferedReader, Data.class);
        List<Rule> rules = data.getRules();

        for (Rule rule : rules) {
            System.out.println("element: " + rule.getElement());
            System.out.println("skip: " + rule.isSkip());
        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.