将 JSON 字符串转换为 Java ME 中的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1395551/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:37:59  来源:igfitidea点击:

Convert a JSON string to object in Java ME?

javajsonjava-meserialization

提问by TheFlash

Is there a way in Java/J2ME to convert a string, such as:

Java/J2ME 中有没有办法转换字符串,例如:

{name:"MyNode", width:200, height:100}

to an internal Object representation of the same, in one line of code?

到相同的内部对象表示,在一行代码中?

Because the current method is too tedious:

因为现在的方法太繁琐了:

Object n = create("new");
setString(p, "name", "MyNode");
setInteger(p, "width", 200);
setInteger(p, "height", 100);

Maybe a JSON library?

也许是一个 JSON 库?

采纳答案by ZZ Coder

I used a few of them and my favorite is,

我使用了其中的一些,我最喜欢的是,

http://code.google.com/p/json-simple/

http://code.google.com/p/json-simple/

The library is very small so it's perfect for J2ME.

该库非常小,因此非常适合 J2ME。

You can parse JSON into Java object in one line like this,

您可以像这样在一行中将 JSON 解析为 Java 对象,

JSONObject json = (JSONObject)new JSONParser().parse("{\"name\":\"MyNode\", \"width\":200, \"height\":100}");
System.out.println("name=" + json.get("name"));
System.out.println("width=" + json.get("width"));

回答by Esteban Küber

You have many JSON parsers for Java:

您有许多用于 Java 的 JSON 解析器

  • JSONObject.java
    A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONArray.java
    A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.

  • JSONStringer.java
    A JSONStringer is a tool for rapidly producing JSON text.

  • JSONWriter.java
    A JSONWriter is a tool for rapidly writing JSON text to streams.

  • JSONTokener.java
    A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and JSONArray constructors to parse JSON source strings.

  • JSONException.java
    A JSONException is thrown when a syntax or procedural error is detected.

  • JSONString.java
    The JSONString is an interface that allows classes to implement their JSON serialization.

  • JSONObject.java
    JSONObject 是名称/值对的无序集合。它的外部形式是用花括号包裹的字符串,名称和值之间用冒号,值和名称之间用逗号。内部形式是一个对象,具有用于按名称访问值的 get() 和 opt() 方法,以及用于按名称添加或替换值的 put() 方法。值可以是以下任何类型:Boolean、JSONArray、JSONObject、Number 和 String,或 JSONObject.NULL 对象。

  • JSONArray.java
    JSONArray 是有序的值序列。它的外部形式是一个用方括号括起来的字符串,值之间有逗号。内部形式是一个对象,具有用于通过索引访问值的 get() 和 opt() 方法,以及用于添加或替换值的 put() 方法。值可以是以下任何类型:Boolean、JSONArray、JSONObject、Number 和 String,或 JSONObject.NULL 对象。

  • JSONStringer.java
    JSONStringer 是一种用于快速生成 JSON 文本的工具。

  • JSONWriter.java
    JSONWriter 是一种将 JSON 文本快速写入流的工具。

  • JSONTokener.java
    JSONTokener 获取源字符串并从中提取字符和标记。JSONObject 和 JSONArray 构造函数使用它来解析 JSON 源字符串。

  • JSONException.java
    检测到语法或程序错误时抛出 JSONException。

  • JSONString.java
    JSONString 是一个接口,允许类实现它们的 JSON 序列化。

回答by Pierre

Apart from www.json.orgyou can also implement your own parser using javaccand matching your personnal grammar/schema. See this note on my blog : http://plindenbaum.blogspot.com/2008/07/parsing-json-with-javacc-my-notebook.html

除了www.json.org,您还可以使用javacc实现您自己的解析器并匹配您的个人语法/模式。在我的博客上看到这个注释:http: //plindenbaum.blogspot.com/2008/07/parsing-json-with-javacc-my-notebook.html

回答by Steve Reed

I've written a library that uses json.org to parse JSON, but it will actually create a proxy of an interface for you. The code/JAR is on code.google.com.

我编写了一个使用 json.org 解析 JSON 的库,但它实际上会为您创建一个接口代理。代码/JAR 位于 code.google.com 上。

http://fixjures.googlecode.com/

http://fixjures.googlecode.com/

I don't know if it works on J2ME. Since it uses Java Reflection to create proxies, I'm thinking it won't work. Also, it's currently got a hard dependency on Google Collections which I want to remove and it's probably too heavyweight for your needs, but it allows you to interact with your JSON data in the way you're looking for:

我不知道它是否适用于 J2ME。由于它使用 Java 反射来创建代理,我认为它不起作用。此外,它目前对我想删除的 Google Collections 有一个硬依赖,它可能对您的需求来说太重了,但它允许您以您正在寻找的方式与您的 JSON 数据进行交互:

interface Foo {
    String getName();
    int getWidth();
    int getHeight();
}

Foo myFoo = Fixjure.of(Foo.class).from(JSONSource.newJsonString("{ name : \"foo name\" }")).create();
String name = myFoo.getName(); // name now .equals("foo name");

回答by Alok Vaish

GSON is a good option to convert java object to json object and vise versa.
It is a tool provided by google.

GSON 是一个很好的选择,可以将 java 对象转换为 json 对象,反之亦然。
它是谷歌提供的工具。

for converting json to java object use: fromJson(jsonObject,javaclassname.class)
for converting java object to json object use: toJson(javaObject)
and rest will be done automatically

用于将 json 转换为 java 对象使用:fromJson(jsonObject,javaclassname.class)
用于将 java 对象转换为 json 对象使用:toJson(javaObject)
其余将自动完成

For more information and for download

欲了解更多信息和下载

回答by tzik

JSON official siteis where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-libwhich is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.

JSON 官方网站是您应该查看的地方。它提供了可以与 Java 一起使用的各种库,我个人使用过这个,JSON-lib,它是站点中工作的实现,因此它在此页面中具有完全相同的类 - 方法等。

If you click the html links there you can find anything you want.

如果您单击那里的 html 链接,您可以找到任何您想要的东西。

In short:

简而言之:

to create a json object and a json array, the code is:

创建一个json对象和一个json数组,代码为:

JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);

o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.

o1、o2 可以是原始类型(long、int、boolean)、字符串或数组。

The reverse process is fairly simple, I mean converting a string to json object/array.

反向过程相当简单,我的意思是将字符串转换为 json 对象/数组。

String myString;

JSONObject obj = new JSONObject(myString);

JSONArray array = new JSONArray(myString);

In order to be correctly parsed you just have to know if you are parsing an array or an object.

为了正确解析,您只需要知道您是在解析数组还是对象。

回答by StaxMan

The simplest option is Hymanson:

最简单的选择是Hymanson

MyObject ob = new ObjectMapper().readValue(jsonString, MyObject.class);

There are other similarly simple to use libraries (Gson was already mentioned); but some choices are more laborious, like original org.json library, which requires you to create intermediate "JSONObject" even if you have no need for those.

还有其他类似的简单易用的库(已经提到了 Gson);但是有些选择更费力,比如原始的 org.json 库,它需要你创建中间的“JSONObject”,即使你不需要那些。

回答by sufinawaz

You can do this easily with Google GSON.

您可以使用 Google GSON 轻松完成此操作。

Let's say you have a class called User with the fields user, width, and height and you want to convert the following json string to the User object.

假设您有一个名为 User 的类,其中包含字段 user、width 和 height,并且您想将以下 json 字符串转换为 User 对象。

{"name":"MyNode", "width":200, "height":100}

{"name":"MyNode", "width":200, "height":100}

You can easily do so, without having to cast (keeping nimcap's comment in mind ;) ), with the following code:

你可以很容易地做到这一点,而无需强制转换(记住 nimcap 的评论 ;) ),使用以下代码:

Gson gson = new Gson(); 
final User user = gson.fromJson(jsonString, User.class);

Where jsonString is the above JSON String.

其中 jsonString 是上述 JSON 字符串。

For more information, please look into https://code.google.com/p/google-gson/

有关更多信息,请查看https://code.google.com/p/google-gson/

回答by Josue Alexander Ibarra

JSON IO is by far the easiest way to convert a JSON string or JSON input stream to a Java Object

JSON IO 是迄今为止将 JSON 字符串或 JSON 输入流转换为 Java 对象的最简单方法

String to Java Object
Object obj = JsonReader.jsonToJava("[\"Hello, World\"]");

字符串到 Java 对象
Object obj = JsonReader.jsonToJava("[\"Hello, World\"]");

https://code.google.com/p/json-io/

https://code.google.com/p/json-io/

回答by Ashish Aggarwal

Use google GSONlibrary for this

为此使用谷歌GSON

public static <T> T getObject(final String jsonString, final Class<T> objectClass) {  
    Gson gson = new Gson();  
    return gson.fromJson(jsonString, objectClass);  
}

http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html

http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html