Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6165365
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T22:09:03+00:00 2026-05-23T22:09:03+00:00

Given a complex object hierarchy, which luckily contains no cyclic references, how do I

  • 0

Given a complex object hierarchy, which luckily contains no cyclic references, how do I implement serialization with support for various formats? I’m not here to discuss an actual implementation. Instead, I’m looking for hints on design patterns which might come in handy.

To be a little more precise: I’m using Ruby and I want to parse XML and JSON data to build up a complex object hierarchy. Furthermore, it should be possible to serialize this hierarchy to JSON, XML, and possibly HTML.

Can I utilize the Builder pattern for this? In any of the mentioned cases, I have some sort of structured data – either in memory or textual – which I want to use to build up something else.

I think it would be nice to separate the serialization logic from the actual business logic, so that I can easily support multiple XML formats later on.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T22:09:05+00:00Added an answer on May 23, 2026 at 10:09 pm

    I ended up creating a solution which is based on the Builder and the Strategy pattern. I’m using the Builder pattern to extract parsing and building logic into there own classes. This allows me to easily add new parsers and builders, respectively. I’m using the Strategy pattern to implement the individual parsing and building logic, because this logic depends on my input and output format.

    The figure below shows a UML diagram of my solution.

    Parser/Builder Model

    The listing below shows my Ruby implementation. The implementation is somewhat trivial because the object I’m building is fairly simple. For those of you who think that this code is bloated and Java-ish, I think this is actually good design. I admit, in such a trivial case I could have just build the construction methods directly into my business object. However, I’m not constructing fruits in my other application, but fairly complex objects instead, so separating parsing, building, and business logic seems like a good idea.

    require 'nokogiri'
    require 'json'
    
    class Fruit
    
      attr_accessor :name
      attr_accessor :size
      attr_accessor :color
    
      def initialize(attrs = {})
        self.name = attrs[:name]
        self.size = attrs[:size]
        self.color = attrs[:color]
      end
    
      def to_s
        "#{size} #{color} #{name}"
      end
    
    end
    
    class FruitBuilder
    
      def self.build(opts = {}, &block)
        builder = new(opts)
        builder.instance_eval(&block)
        builder.result
      end
    
      def self.delegate(method, target)
        method = method.to_sym
        target = target.to_sym
    
        define_method(method) do |*attrs, &block|
          send(target).send(method, *attrs, &block)
        end
      end
    
    end
    
    class FruitObjectBuilder < FruitBuilder
    
      attr_reader :fruit
    
      delegate :name=,  :fruit
      delegate :size=,  :fruit
      delegate :color=, :fruit
    
      def initialize(opts = {})
        @fruit = Fruit.new
      end
    
      def result
        @fruit
      end
    
    end
    
    class FruitXMLBuilder < FruitBuilder
    
      attr_reader :document
    
      def initialize(opts = {})
        @document = Nokogiri::XML::Document.new
      end
    
      def name=(name)
        add_text_node(root, 'name', name)
      end
    
      def size=(size)
        add_text_node(root, 'size', size)
      end
    
      def color=(color)
        add_text_node(root, 'color', color)
      end
    
      def result
        document.to_s
      end
    
      private
    
      def add_text_node(parent, name, content)
        text = Nokogiri::XML::Text.new(content, document)
        element = Nokogiri::XML::Element.new(name, document)
    
        element.add_child(text)
        parent.add_child(element)
      end
    
      def root
        document.root ||= create_root
      end
    
      def create_root
        document.add_child(Nokogiri::XML::Element.new('fruit', document))
      end
    
    end
    
    class FruitJSONBuilder < FruitBuilder
    
      attr_reader :fruit
    
      def initialize(opts = {})
        @fruit = Struct.new(:name, :size, :color).new
      end
    
      delegate :name=,  :fruit
      delegate :size=,  :fruit
      delegate :color=, :fruit
    
      def result
        Hash[*fruit.members.zip(fruit.values).flatten].to_json
      end
    
    end
    
    class FruitParser
    
      attr_reader :builder
    
      def initialize(builder)
        @builder = builder
      end
    
      def build(*attrs, &block)
        builder.build(*attrs, &block)
      end
    
    end
    
    class FruitObjectParser < FruitParser
    
      def parse(other_fruit)
        build do |fruit|
          fruit.name  = other_fruit.name
          fruit.size  = other_fruit.size
          fruit.color = other_fruit.color
        end
      end
    
    end
    
    class FruitXMLParser < FruitParser
    
      def parse(xml)
        document = Nokogiri::XML(xml)
    
        build do |fruit|
          fruit.name  = document.xpath('/fruit/name').first.text.strip
          fruit.size  = document.xpath('/fruit/size').first.text.strip
          fruit.color = document.xpath('/fruit/color').first.text.strip
        end
      end
    
    end
    
    class FruitJSONParser < FruitParser
    
      def parse(json)
        attrs = JSON.parse(json)
    
        build do |fruit|
          fruit.name  = attrs['name']
          fruit.size  = attrs['size']
          fruit.color = attrs['color']
        end
      end
    
    end
    
    # -- Main program ----------------------------------------------------------
    
    p = FruitJSONParser.new(FruitXMLBuilder)
    puts p.parse('{"name":"Apple","size":"Big","color":"Red"}')
    
    p = FruitXMLParser.new(FruitObjectBuilder)
    puts p.parse('<fruit><name>Apple</name><size>Big</size><color>Red</color></fruit>')
    
    p = FruitObjectParser.new(FruitJSONBuilder)
    puts p.parse(Fruit.new(:name => 'Apple', :color => 'Red', :size => 'Big'))
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Given an object A, which contains a callable object B, is there a way
given a somewhat complex file of unknown specification that among other things contains an
Given an aggregation of class instances which refer to each other in a complex,
Got a complex reflection question. Given the code below how would you implement the
Given a fairly complex object with lots of state, is there a pattern for
As I understood , The property grid is given an object which it can
I've created a complex object which itself include a list of another object. Example:
Given the code from the Complex Form part III how would you go about
Given an HTML page that has a complex table-based layout and many tags that
Given a Python object of any kind, is there an easy way to get

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.