Rectangle 27 40

int spacesToIndentEachLevel = 2;
new JSONObject(jsonString).toString(spacesToIndentEachLevel);

Using org.json.JSONObject (built in to JavaEE and Android)

What library does this use? As is it is not a very helpful answer.

@Andrew Backer, this is not a library. As Heath Borders said, it is built into the Android libraries. I've tested this and it works perfectly without any libraries.

Hm... I'm not developing for Android, and I don't deploy to a java EE container... hence the need for clarification. Thanks for adding that :) So for someone like me, distributing a java app targeting SE, it would be a library such as org.json:json:20090211?

for those of us using Android, this is very useful and not really clear in the quick view of the docs. Didn't expect it to be built in.

org.json.JSONObject
JSON-P
JsonObject
javax.json.JsonObject

How do I pretty-print existing JSON data with Java? - Stack Overflow

java json formatting pretty-print
Rectangle 27 2

I doubt this is possible with a POJO-JSON mapper. You could use libraries like json-simple to parse the JSON string into Java objects (which basically are maps and lists) and access values like "10869918" by reading the keys of those maps.

My idea exactly; don't map to an object, map to a collection instead. The data itself seems to represent a hashtable of sorts anyway, so it would be pretty strange to want to map that to a POJO.

How to parse JSON data without key names into a Java class structure? ...

java json jackson anonymous-types class-structure
Rectangle 27 9

String niceFormattedJson = JsonWriter.formatJson(jsonString)
System.out.println(JsonWriter.formatJson(jsonString.toString()));

The json-io libray (https://github.com/jdereg/json-io) is a small (75K) library with no other dependencies than the JDK.

In addition to pretty-printing JSON, you can serialize Java objects (entire Java object graphs with cycles) to JSON, as well as read them in.

Used this little library, with some modifications to the output format. Thanks for letting me know about it.

Not only was this the first solution to work on my environment, it finally confirmed that I know how to use Gradle to properly pull in thrid-party libraries! A good day, Thanks!

How do I pretty-print existing JSON data with Java? - Stack Overflow

java json formatting pretty-print
Rectangle 27 2

I'd be more concerned with what looks like metadata fields in the data stream. The top level 'abort' and 'more' attributes look like some kind of structured string which you may have to parse? Aside from that, you just need to model each Java object with the widest possible set of fields that will be sent from your external program. You don't have to worry if transmitted data has one or more of the fields missing, most JSON libraries will just deserialize a null in that case. Also, most of the JSON libraries will also allow you to specify that you want to ignore unknown incoming fields.

So between deserializing null for missing fields and ignoring extra fields, you should be good to go for your parse.

So you are saying that extra fields in the json stream are ignored? I'm going to go out on a limb and guess that depends on the library?

Yes, it depends on the library and more to the point, the configuration of said library. For example, this behavior is off by default in Jackson but can be turned on with a configuration setting.

I can't seem to up-vote or mark more than one as an answer. I'd mark this one as an answer as well. Thanks for the help.

No problem, good luck with the rest of the project.

JSON to Java Objects, best practice for modeling the json stream - Sta...

java json deserialization
Rectangle 27 2

You may use this JSON library to parse your json string into JSONObject and read value from that object as show below :

JSONObject json = new JSONObject(EntityUtils.toString(entity));
JSONObject sessionObj =  json.getJSONObject("session");
System.out.println(sessionObj.getString("name"));

You need to read upto that object from where you want to read value. Here you want the value of name parameter which is inside that session object, so you first get the value of session as JSONObject using getJSONObject(KeyString) and read name value from that object using function getString(KeyString) as show above.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

how to manipulate HTTP json response data in Java - Stack Overflow

java json http httpresponse
Rectangle 27 4

If you are using jackson you can easily achieve this with configuring a SerializationFeature in your ObjectMapper:

com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();

mapper.configure(SerializationFeature.INDENT_OUTPUT, true);

mapper.writeValueAsString(<yourObject>);

How do I pretty-print existing JSON data with Java? - Stack Overflow

java json formatting pretty-print
Rectangle 27 3

To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.

Of course you can do similar with any JSON library you like.

How do I pretty-print existing JSON data with Java? - Stack Overflow

java json formatting pretty-print
Rectangle 27 4

if you are using jquery on the client side, this worked for me:

@RequestMapping(value = "/ajax/search/sync") 
public ModelAndView sync(@RequestBody SearchRequest json) {
$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});

Parsing json into java objects in spring-mvc - Stack Overflow

java json spring-mvc jackson
Rectangle 27 4

if you are using jquery on the client side, this worked for me:

@RequestMapping(value = "/ajax/search/sync") 
public ModelAndView sync(@RequestBody SearchRequest json) {
$.ajax({
    type: "post",
    url: "sync", //your valid url
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me)
    data: JSON.stringify(jsonobject), //json object or array of json objects
    success: function(result) {
        //do nothing
    },
    error: function(){
        alert('failure');
    }
});

Parsing json into java objects in spring-mvc - Stack Overflow

java json spring-mvc jackson
Rectangle 27 2

Using a different property name in the JSON than in the Java code

The 9.x (and higher) versions of the Firebase SDK for Android/Java stopped including Jackson for serializing/deserializing Java<->JSON. The newer SDK instead provides a minimal set of custom annotations to allow control over the most common customization needs, while having a minimal impact on the resulting JAR/APK size.

  • Using the Firebase 2.x SDKs
  • Using the Firebase 9.0 or higher SDKs, but [use Jackson for serializing/deserializing Java<->JSON](TODO: link to answer).

We'll start with this JSON structure in our Firebase Database:

{
  "-Jx86I5e8JBMZ9tH6W3Q" : {
    "handle" : "puf",
    "name" : "Frank van Puffelen",
    "stackId" : 209103,
    "stackOverflowId" : 209103
  },
  "-Jx86Ke_fk44EMl8hRnP" : {
    "handle" : "mimming",
    "name" : "Jenny Tong",
    "stackId" : 839465
  },
  "-Jx86N4qeUNzThqlSMer" : {
    "handle" : "kato",
    "name" : "Kato Wulf",
    "stackId" : 394010
  }
}

At its most basic, we can load each user from this JSON into the following Java class:

If we declare the fields to be public, we don't even need the getters:

private static class CompleteUser {
    public String handle;
    public String name;
    public long stackId;
}

We can also partially load a user, for example with:

private static class PartialUser {
    String handle;
    String name;

    public String getHandle() {
        return handle;
    }
    public String getName() { return name; }

    @Override
    public String toString() {
        return "User{handle='" + handle + "', NAME='" + name + "''}";
    }
}

When we use this class to load the users from the same JSON, the code runs (unlike the Jackson variant mentioned in my other answer). But you'll see a warning in your logging output:

So get rid of that, we can annotate the class with @IgnoreExtraProperties:

@IgnoreExtraProperties
private static class PartialUser {
    String handle;
    String name;

    public String getHandle() {
        return handle;
    }
    public String getName() { return name; }

    @Override
    public String toString() {
        return "User{handle='" + handle + "', NAME='" + name + "''}";
    }
}

As before, you might want to add a calculated property to the user. You'd want to ignore such a property when saving the data back to the database. To do this, you can annotate the property/getter/setter/field with @Exclude:

private static class OvercompleteUser {
    String handle;
    String name;
    long stackId;

    public String getHandle() { return handle; }
    public String getName() { return name; }
    public long getStackId() { return stackId; }

    @Exclude
    public String getTag() { return getName() + " ("+getHandle()+")"; }

    @Override
    public String toString() { return "User{handle='"+handle+"', name='"+name+"', stackId="+stackId+ "'}"; }
}

Now when writing a user to the database, the value of getTag() will be ignored.

You can also specify what name a field/getter/setter from the Java code should get in the JSON in the database. To do this: annotate the field/getter/setter with @PropertyName().

private static class UserWithRenamedProperty {
    String handle;
    String name;
    @PropertyName("stackId")
    long stackOverflowId;

    public String getHandle() { return handle; }
    public String getName() { return name; }
    @PropertyName("stackId")
    public long getStackOverflowId() { return stackOverflowId; }

    @Override
    public String toString() { return "User{handle='"+handle+"', name='"+name+"', stackId="+stackOverflowId+ "'}"; }
}

In general it's best to use the default mapping between Java<->JSON that the Firebase SDK uses. But @PropertyName may be needed when you have a pre-existing JSON structure that you can't otherwise map to Java classes.

android - Why do I get "Failed to bounce to type" when I turn JSON fro...

java android firebase firebase-database
Rectangle 27 4

Do you mean, you know what the types of Thing will be at the time that you read the value? Because in that case, you could parameterise Data (i.e. Data<T extends Thing>), and propagate the type parameter to Datum to specify the subclass of Thing that you have. And then you need to tell Jackson about the parameterised type when you call readValue, which can be done statically like this:

mapper.readValue(jsonString, new TypeReference<Data<Prisoner>>(){});

It can be done dynamically by constructing a parameterised type using the TypeFactory available from the ObjectMapper. Something like:

mapper.readValue("", mapper.getTypeFactory()
                           .constructParametricType(Data.class, thingSubclass));

java - How do I deserialize an array of JSON data into a POJO using an...

java json jackson deserialization pojo
Rectangle 27 1

I think the Jackson data mapper can do what you need. It can serialize/deserialize a real Java object into a Json tree.

But others API should also work :

JSON to Objects in java? - Stack Overflow

java json
Rectangle 27 14

You have two ways. Either you create a database and save all of the data there and retrieve it back when you want to. Or if the data you have is not that much and you don't want to deal with databases, then you write the json string to a text file in the memory card and read it later when you are offline.

And for the second case, every time you go online, you can retrieve the same json from your web service and over write it to the old one. This way you can be sure that you have the latest json saved to the device.

Depending on the JSON (if it is couple of entries), @user3241084 can use SharedPreferences.

@YordanLyubenov considering that user wants to store JSON object programatically when it's offline, I don't think it's just a couple of entries.

how can I add this to my code? I just tried but nothin worked?

just deleted the wrong code that my app runs ;)

java - How to Cache Json data to be available offline? - Stack Overflo...

java android json offline
Rectangle 27 1

I fount a very simple solution:

<dependency>
    <groupId>com.cedarsoftware</groupId>
    <artifactId>json-io</artifactId>
    <version>4.5.0</version>
</dependency>
import com.cedarsoftware.util.io.JsonWriter;
//...
String jsonString = "json_string_plain_text";
System.out.println(JsonWriter.formatJson(jsonString));

How do I pretty-print existing JSON data with Java? - Stack Overflow

java json formatting pretty-print
Rectangle 27 1

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(my_bean);
{
  "name": "mkyong",
  "age": 35,
  "position": "Founder",
  "salary": 10000,
  "skills": [
    "java",
    "python",
    "shell"
  ]
}

How do I pretty-print existing JSON data with Java? - Stack Overflow

java json formatting pretty-print
Rectangle 27 6

Your JSON is not an array.

It's a JSON object with one property: modeles, whose value is the array.

Parse the root as JsonObject.

You got to love a library construct for interpreting a format that requires you to understand the format and know what you've got before you interpret it!

How to convert a json data to string in java - Stack Overflow

java json arrays jsonobject
Rectangle 27 7

They way you send your data, using HTTP POST, you're posting the JSON as request body, not as request attributes. This means you shouldn't use request.attribute("item") and the others, but instead parse the request body to a Java object. You can use that object to create the element and store it using the DAO.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

javascript - How read data sent by Client with Spark? - Stack Overflow

javascript jquery httprequest spark-java
Rectangle 27 7

They way you send your data, using HTTP POST, you're posting the JSON as request body, not as request attributes. This means you shouldn't use request.attribute("item") and the others, but instead parse the request body to a Java object. You can use that object to create the element and store it using the DAO.

javascript - How read data sent by Client with Spark? - Stack Overflow

javascript jquery httprequest spark-java
Rectangle 27 18

private JSONObject uploadToServer() throws IOException, JSONException {
            String query = "https://example.com";
            String json = "{\"key\":1}";

            URL url = new URL(query);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");

            OutputStream os = conn.getOutputStream();
            os.write(json.getBytes("UTF-8"));
            os.close();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());
            String result = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
            JSONObject jsonObject = new JSONObject(result);


            in.close();
            conn.disconnect();

            return jsonObject;
    }

POST request send json data java HttpUrlConnection - Stack Overflow

java json post curl httpurlconnection
Rectangle 27 10

JPA is a specification for accessing, persisting and managing the data between Java objects and the relational database. As the definition says its API, it is only the specification. There is no implementation for the API. JPA specifies the set of rules and guidelines for developing the interfaces that follows standard. Straight to the point : JPA is just guidelines to implement the Object Relational Mapping (ORM) and there is no underlying code for the implementation.

Where as, Hibernate is the actual implementation of JPA guidelines. When hibernate implements the JPA specification, this will be certified by the JPA group upon following all the standards mentioned in the specification. For example, JPA guidelines would provide information of mandatory and optional features to be implemented as part of the JPA implementation.

Hibernate is a JPA provider. When there is new changes to the specification, hibernate would release its updated implementation for the JPA specification.

java - What's the difference between JPA and Hibernate? - Stack Overfl...

java hibernate jpa java-ee orm