-1

I was given a String in java method and have to return the son depth of that string

like if the method is

find depthJSON(String s){
     //code
     return count;
}

for example:

{
    "0" : { "name" : "John", "City" : "NY"},
    "1" : { "name" : "Mike", "City" : "LA"}
}

for this input, depth is 2

  • 2
    To read a JSON string in Java, see [How to parse JSON in Java](https://stackoverflow.com/q/2591098/5221149). How to check the depth depends on which parser you choose, so we cannot answer that, given the current broadness of the question. – Andreas Apr 08 '20 at 09:47

3 Answers3

1

Your problem calls for a JSON Tokenizer. You do not actually need to parse your file ( ie. build some tree structure as a Java object ) as you are only interested in the maximal nesting depth which can be deduced from the token stream alone.

The basic idea is to keep tabs on the tokens that represent the start and end of an object ( {, } ). Whenever the tokenizer sees an object start/end, increment/decrement a global depth counter; Whenever the tokenizer sees an object end, check whether the current global depth counter is greater than the maximum seen so far and change the value accordingly.

As a package to furnish the JSON Tokenizer, I'd suggest Jackson. Download the jar files into your source directory (or to the suitable place in your development toolset directory). The jar files are available at:

 https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.10.3/jackson-core-2.10.3.jar
 https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.10.3/jackson-annotations-2.10.3.jar
 https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.10.3/jackson-databind-2.10.3.jar

Note that you need all of them and do not forget to alter the Java CLASSPATH unless your IDE takes care of that.

Code

The following class determines and prints the depth of your json:

//  https://stackoverflow.com/questions/61097605/finding-the-depth-of-a-json-string-in-java
//
//  javac.exe -cp "./jackson-core-2.10.3.jar;./jackson-annotations-2.10.3.jar;./jackson-databind-2.10.3.jar" .\json_nesting.java
//  java.exe -cp "./jackson-core-2.10.3.jar;./jackson-annotations-2.10.3.jar;./jackson-databind-2.10.3.jar;." json_nesting
//
//  Cf. https://github.com/FasterXML/jackson-databind#5-minute-tutorial-streaming-parser-generator
//
//  Jar downloads
//      https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core/2.10.3/jackson-core-2.10.3.jar
//      https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-annotations/2.10.3/jackson-annotations-2.10.3.jar
//      https://repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-databind/2.10.3/jackson-databind-2.10.3.jar
//

import java.lang.*;
import java.io.*;
import java.nio.*;

import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.ObjectMapper;

public class json_nesting {
    public static void main(String[] args) {
    // write your code here
        // Second: read file back
        String fpath = "<file path goes here>"; // Double backslashes on Windows ! 
        ObjectMapper mapper = new ObjectMapper(); // create once, reuse
        JsonFactory f = mapper.getFactory();
        try {
            JsonParser p = f.createParser(new File(fpath));

            JsonToken t = p.nextToken();

            int currentDepth = 0;
            int maxDepth = 0;

            while (t != null) {
                if (t == JsonToken.START_OBJECT) {
                    currentDepth++;
                } else {
                    if (t == JsonToken.END_OBJECT) {
                        if (currentDepth > maxDepth) {
                            maxDepth = currentDepth;
                        }
                        currentDepth--;
                    }
                }

                t = p.nextToken();
            };

            System.out.printf("Max depth = %4d.\n", maxDepth);
            p.close();
        } catch ( IOException ioe ) {
            System.out.printf("File processing failed: = '%s'. Message: %s.\n", fpath, ioe.getMessage());
        }
    }
}

Tested with Java SE 11, u 28.

Note (JSON syntax)

Note that your sample file is NOT valid JSON - some property names are not enclosed in double quotes, properties are not separated with commas. A rectified version comes here:

{
    "0" : { "name" : "John", "City" : "NY"}
  , "1" : { "name" : "Mike", "City" : "LA"}
}
collapsar
  • 17,010
  • 4
  • 35
  • 61
0
public static int levelCount(String word) {

    int current= 0;
    int max = 0;

    for (int i = 0; i < word.length(); i++) {
        if (word.charAt(i) == '{') {
            current++;
        
        } else {
            if (word.charAt(i) == '}') {
                if (current > max) {
                    max = current;
                }
                current--;
            }
        }
    }
    return max;
}
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 22 '22 at 10:58
-1

my answer is

    int JsonDepth (String S) { 
        int current_max = 0; 
        int max = 0; 
        int n = S.length(); 

        for (int i = 0; i < n; i++) { 
            if (S.charAt(i) == '{') { 
                current_max++; 

                // update max if required 
                if (current_max > max) { 
                    max = current_max; 
                } 
            } else if (S.charAt(i) == '}') { 
                if (current_max > 0) { 
                    current_max--; 
                } else { 
                    return -1; 
                } 
            } 
        } 

        if (current_max != 0) { 
            return -1; 
        } 

        return max; 
    }