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

  • SEARCH
  • Home
  • 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 6740749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T11:38:36+00:00 2026-05-26T11:38:36+00:00

I have created a class that allows the resulting object to have arbitrary properties

  • 0

I have created a class that allows the resulting object to have arbitrary properties added to it. The class also has some predefined properties. In a method of the class I want to be able to iterate over all properties owned by the instance of the object.

Here is an example class definition:

import groovy.json.*

class Foo {
    private Map props = [:]

    String bar = "baz"
    def myNumber = 42

    void propertyMissing(String name, Object value) {
        this.props[name] = value
    }

    def propertyMissing(String name) {
        return this.props[name]
    }

    def toJsonString() {
        def outObject = [:]

        // I want to do something like this
        this.properties.each { k, v ->
            if (this.isOwnProperty(k) && k != 'props') {
                outObject[k] = v
            }
        }

        outObject = outObject + this.props

        return JsonOutput.toJson(outObject)
        // Should return a string like:
        // {"bar":"baz", "myNumber":42, "someDynamicProperty":"value"}
        //
        // This string should not contain the "class" and "metaClass"
        // properties.
    }
}

Is there a way to do what I am wanting to do?

Edit:
One of my goals is to not have to explicitly name my predefined properties in the toJsonString method. I want to be able to add new predefined properties at a later date without having to remember to update the toJsonString method.

Edit (24 October 2011):

The accepted answer gave me the information I needed. However, it still required me to name the properties I don’t want included in the JSON string. Extending the answer a little bit solves this problem:

def outObject = Foo.declaredFields.findAll {
    // 'it' is a Field object returned by
    // http://download.oracle.com/javase/1,5,0/docs/api/java/lang/Class.html#getDeclaredFields()
    !it.synthetic &&
    it.getModifiers() != java.lang.reflect.Modifier.PRIVATE
}.collectEntries { v ->
    [ (v.name) : this[v.name] ]
}

For this to work, you must explicitly specify the modifiers for your class properties. That is String bar = "baz" in my example should be public String bar = "baz" in order for it to be included in the JSON string.

  • 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-26T11:38:36+00:00Added an answer on May 26, 2026 at 11:38 am

    There’s this possibility (assuming I’ve got the right end of the stick) 😉

    class Foo {
        private Map props = [:]
    
        String bar = "baz"
        def myNumber = 42
    
        void propertyMissing(String name, Object value) {
            this.props[name] = value
        }
    
        def propertyMissing(String name) {
            return this.props[name]
        }
    
        def toJsonString() {
            def outObject = Foo.declaredFields.findAll { !it.synthetic && it.name != 'props' }.collectEntries { v ->
              [ (v.name):this[v.name] ]
            }
            outObject << props
            JsonOutput.toJson(outObject)
        }
    }
    

    If you don’t have Groovy 1.7.9+, then the lines

            def outObject = Foo.declaredFields.findAll { !it.synthetic && it.name != 'props' }.collectEntries { v ->
              [ (v.name):this[v.name] ]
            }
    

    Should be replaced with:

            def outObject = Foo.declaredFields.findAll { !it.synthetic && it.name != 'props' }.inject([:]) { m, v ->
              m << [ (v.name):this[v.name] ]
            }
    

    And I believe it will behave the same; ie: if I do this:

    def f = new Foo()
    f.tim = 'yates'
    println f.toJsonString()
    

    it prints out:

    {"bar":"baz","myNumber":42,"tim":"yates"}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Currently I have created a ABCFactory class that has a single method creating ABC
I have an ExpenseType object that I have created with the following migration: class
I have created a class, MonitoredCollection<T> , that basically encapsulates/mimics List but allows me
I have created a benchmark class that allows the user to insert for example
I have created a benchmark class that allows the user to insert for example
I have created a button CSS class that uses background images with different positions
I have a binary tree class that is created with a root node and
I have created a non-form c# program that uses the NotifyIcon class. The text
I have a collection of classes that inherit from an abstract class I created.
I have a control that is created like so: public partial class MYControl :

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.