|
| 1 | +/* Copyright 2006-2007 Graeme Rocher |
| 2 | + * |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * |
| 7 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + * |
| 9 | + * Unless required by applicable law or agreed to in writing, software |
| 10 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | + * See the License for the specific language governing permissions and |
| 13 | + * limitations under the License. |
| 14 | + */ |
| 15 | +package grails.converters.deep; |
| 16 | + |
| 17 | +import org.codehaus.groovy.grails.web.converters.Converter; |
| 18 | +import org.codehaus.groovy.grails.web.converters.exceptions.ConverterException; |
| 19 | + |
| 20 | +import java.util.HashMap; |
| 21 | +import java.util.Map; |
| 22 | +import java.util.Stack; |
| 23 | + |
| 24 | +/** |
| 25 | + * A converter that converts domain classes, Maps, Lists, Arrays, POJOs and POGOs |
| 26 | + * to JSON (Including nested Domain Classes) |
| 27 | + * |
| 28 | + * @author Siegfried Puchbauer |
| 29 | + */ |
| 30 | +public class JSON extends grails.converters.JSON implements Converter { |
| 31 | + |
| 32 | + private Stack stack = new Stack(); |
| 33 | + |
| 34 | + protected void bean(Object o) throws ConverterException { |
| 35 | + if (stack.contains(o)) { |
| 36 | + //value(new HashMap());//throw new ConverterException("Circular Relationship detected!"); |
| 37 | + handleCircularRelationship(o); |
| 38 | + return; |
| 39 | + } |
| 40 | + stack.push(o); |
| 41 | + super.bean(o); |
| 42 | + stack.pop(); |
| 43 | + } |
| 44 | + |
| 45 | + protected void domain(Object o) throws ConverterException { |
| 46 | + if (stack.contains(o)) { |
| 47 | + //value(new HashMap());//throw new ConverterException("Circular Relationship detected!"); |
| 48 | + handleCircularRelationship(o); |
| 49 | + return; |
| 50 | + } |
| 51 | + stack.push(o); |
| 52 | + super.domain(o); |
| 53 | + stack.pop(); |
| 54 | + } |
| 55 | + |
| 56 | + protected void handleCircularRelationship(Object o) throws ConverterException { |
| 57 | + Map props = new HashMap(); |
| 58 | + props.put("class", o.getClass()); |
| 59 | + StringBuffer ref = new StringBuffer(); |
| 60 | + int idx = stack.indexOf(o); |
| 61 | + for (int i = stack.size(); i > idx; i--) { |
| 62 | + ref.append("../"); |
| 63 | + } |
| 64 | + props.put("_ref", ref.substring(0, ref.length() - 1)); |
| 65 | + value(props); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * internal Getter |
| 70 | + * |
| 71 | + * @return true |
| 72 | + */ |
| 73 | + public boolean isRenderDomainClassRelations() { |
| 74 | + return true; |
| 75 | + } |
| 76 | +} |
0 commit comments