转换JSON代码的最佳方法是:
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
Run Code Online (Sandbox Code Playgroud)
在Java Map中,其中一个键是(field1,field2),这些字段的值是(value1,value2).
有任何想法吗?我应该使用Json-lib吗?或者更好,如果我写自己的解析器?
我需要将json字符串转换为java对象并将其显示为long.json字符串是一个固定的长数组:
{numbers
[ 268627104, 485677888, 506884800 ] }
Run Code Online (Sandbox Code Playgroud)
转换的代码在所有情况下都可以正常工作,除了以0结尾的数字.它将这些转换为科学记数字格式:
public static Object fromJson(HttpResponse response, Class<?> classOf)
throws IOException {
InputStream instream = response.getResponseInputStream();
Object obj = null;
try {
Reader reader = new InputStreamReader(instream, HTTP.UTF_8);
Gson gson = new Gson();
obj = gson.fromJson(reader, classOf);
Logger.d(TAG, "json --> "+gson.toJson(obj));
} catch (UnsupportedEncodingException e) {
Logger.e(TAG, "unsupported encoding", e);
} catch (Exception e) {
Logger.e(TAG, "json parsing error", e);
}
return obj;
}
Run Code Online (Sandbox Code Playgroud)
实际结果:Java对象:268627104,485677888,5.068848E + 8
请注意,最后一个数字将转换为科学记数法格式.任何人都可以建议可以做些什么来解决它或阻止或撤消它?我正在使用Gson v1.7.1
嗨,我可以配置gson,他使用int而不是double获取数据,如:
{fn: chat, data: {roomId: 1, text: "Some brabble"}}
Run Code Online (Sandbox Code Playgroud)
我有一个PacketClass将其反序列化为:
public class DataPacket {
private String fn;
private Object p; // will be a StringMap
}
Run Code Online (Sandbox Code Playgroud)
并解码如下:
DataPacket pkg = gson.fromJson(message, DataPacket.class);
Run Code Online (Sandbox Code Playgroud)
为了更好的类型处理,我得到了DataPacket.p字段的数据pojo,例如:
public class ChatPacket {
public int roomId;
public String message;
public String from;
// getter & setter
}
Run Code Online (Sandbox Code Playgroud)
将数据解析为数据包我使用BeanMaps(我删除了错误处理等):
public Object getData(Class<?> pojoClass) {
pojo = pojoClass.newInstance();
BeanMap b = new BeanMap();
b.setBean(pojo);
b.putAll(this.p);
pojo = b.getBean();
}
Run Code Online (Sandbox Code Playgroud)
问题是现在gson使roomId:1变为StringMap中的双1.0并且beanmap尝试将其解析为整数并抛出NumberFormatException,任何人都知道如何解决这个问题?
谢谢!
我目前正在学习一个教程,以帮助我学习JavaFX的工作原理,在教程中他们正在构建一个小应用来管理人们的信息.本教程还使用XML进行加载/保存,但我不想使用XML并且想要使用JSON.我有一个Person使用的模型StringProperty,IntegerProperty和ObjectProperty.我的问题是,我不确定加载和保存这个的最佳方法是什么,如果没有它保存不必要的字段,也加载没有Gson抛出错误.
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Model class for a Person.
*
* @author Marco Jakob
*/
public class Person {
private final StringProperty firstName;
private final StringProperty lastName;
private final StringProperty street;
private final IntegerProperty postalCode;
private final StringProperty city;
private final ObjectProperty<LocalDate> birthday;
/**
* Default constructor.
*/
public Person() {
this(null, null);
}
/**
* Constructor with …Run Code Online (Sandbox Code Playgroud) 我的json中有整数,我不希望gson将它们转换成双打.以下不起作用:
@Test
public void keepsIntsAsIs(){
String json="[{\"id\":1,\"quantity\":2,\"name\":\"apple\"},{\"id\":3,\"quantity\":4,\"name\":\"orange\"}]";
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Double.class, new DoubleSerializerAsInt());
Gson gson = gsonBuilder.create();
List<Map<String, Object>> l = gson.fromJson(json, List.class);
for(Map<String, Object> item : l){
System.out.println(item);
}
}
private static class DoubleSerializerAsInt implements JsonSerializer<Double>{
@Override
public JsonElement serialize(Double aDouble, Type type, JsonSerializationContext jsonSerializationContext) {
int value = (int)Math.round(aDouble);
return new JsonPrimitive(value);
}
}
Run Code Online (Sandbox Code Playgroud)
输出不是我想要的:
{id=1.0, quantity=2.0, name=apple}
{id=3.0, quantity=4.0, name=orange}
Run Code Online (Sandbox Code Playgroud)
有没有办法在我的地图中使用整数而不是双打?
{id=1, quantity=2, name=apple}
{id=3, quantity=4, name=orange}
Run Code Online (Sandbox Code Playgroud)
编辑:并非所有字段都是整数.我相应地修改了我的例子.我在网上看了很多例子,包括这个网站上的一些答案,但在这个特殊情况下它不起作用.
一个复杂的json字符串,我想将其转换为map,我有一个问题.
请看这个简单的测试:
public class Test {
@SuppressWarnings("serial")
public static void main(String[] args) {
Map<String, Object> hashMap = new HashMap<String, Object>();
hashMap.put("data", "{\"rowNum\":0,\"colNum\":2,\"text\":\"math\"}");
Map<String,Object> dataMap = JsonUtil.getGson().fromJson(
hashMap.get("data").toString(),new TypeToken<Map<String,Object>>() {}.getType());
System.out.println(dataMap.toString());
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
控制台打印:{rowNum=0.0, colNum=2.0, text=math}
Int转换为Double;
为什么gson会更改类型以及如何修复它?
是否可以确定 GSONJsonElement实例是整数还是浮点数?
我能够确定它是否是一个数字:
JsonElement value = ...
boolean isNumber = value.getAsJsonPrimitive().isNumber();
Run Code Online (Sandbox Code Playgroud)
但是如何确定它是整数还是浮点数,以便我随后可以使用正确的转换方法?任何一个
float f = value.getAsJsonPrimitive().getAsFloat();
Run Code Online (Sandbox Code Playgroud)
或者
int i = value.getAsJsonPrimitive().getAsInt();
Run Code Online (Sandbox Code Playgroud)
编辑:另一个问题可能会回答为什么这可能不会在 GSON 中实现,但这个问题绝对不是它的重复。